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..0bbbcac72 100644 --- a/.tx/config +++ b/.tx/config @@ -1,4790 +1,4096 @@ [main] host = https://www.transifex.com -[o:python-doc:p:python-newest:r:about] -file_filter = .//LC_MESSAGES/about.po -trans.pt_BR = about.po -source_file = ../../pot/about.pot +[o:python-doc:p:python-313:r:about] +file_filter = about.po 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 -trans.pt_BR = bugs.po -source_file = ../../pot/bugs.pot +[o:python-doc:p:python-313:r:bugs] +file_filter = bugs.po 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 -trans.pt_BR = c-api/abstract.po -source_file = ../../pot/c-api/abstract.pot +[o:python-doc:p:python-313:r:c-api--abstract] +file_filter = c-api/abstract.po 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 -trans.pt_BR = c-api/allocation.po -source_file = ../../pot/c-api/allocation.pot +[o:python-doc:p:python-313:r:c-api--allocation] +file_filter = c-api/allocation.po 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 -trans.pt_BR = c-api/apiabiversion.po -source_file = ../../pot/c-api/apiabiversion.pot +[o:python-doc:p:python-313:r:c-api--apiabiversion] +file_filter = c-api/apiabiversion.po 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 -trans.pt_BR = c-api/arg.po -source_file = ../../pot/c-api/arg.pot +[o:python-doc:p:python-313:r:c-api--arg] +file_filter = c-api/arg.po 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 -trans.pt_BR = c-api/bool.po -source_file = ../../pot/c-api/bool.pot +[o:python-doc:p:python-313:r:c-api--bool] +file_filter = c-api/bool.po 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 -trans.pt_BR = c-api/buffer.po -source_file = ../../pot/c-api/buffer.pot +[o:python-doc:p:python-313:r:c-api--buffer] +file_filter = c-api/buffer.po 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 -trans.pt_BR = c-api/bytearray.po -source_file = ../../pot/c-api/bytearray.pot +[o:python-doc:p:python-313:r:c-api--bytearray] +file_filter = c-api/bytearray.po 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 -trans.pt_BR = c-api/bytes.po -source_file = ../../pot/c-api/bytes.pot +[o:python-doc:p:python-313:r:c-api--bytes] +file_filter = c-api/bytes.po 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 -trans.pt_BR = c-api/call.po -source_file = ../../pot/c-api/call.pot +[o:python-doc:p:python-313:r:c-api--call] +file_filter = c-api/call.po 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 -trans.pt_BR = c-api/capsule.po -source_file = ../../pot/c-api/capsule.pot +[o:python-doc:p:python-313:r:c-api--capsule] +file_filter = c-api/capsule.po 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 -trans.pt_BR = c-api/cell.po -source_file = ../../pot/c-api/cell.pot +[o:python-doc:p:python-313:r:c-api--cell] +file_filter = c-api/cell.po 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 -trans.pt_BR = c-api/code.po -source_file = ../../pot/c-api/code.pot +[o:python-doc:p:python-313:r:c-api--code] +file_filter = c-api/code.po 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 -trans.pt_BR = c-api/codec.po -source_file = ../../pot/c-api/codec.pot +[o:python-doc:p:python-313:r:c-api--codec] +file_filter = c-api/codec.po 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 -trans.pt_BR = c-api/complex.po -source_file = ../../pot/c-api/complex.pot +[o:python-doc:p:python-313:r:c-api--complex] +file_filter = c-api/complex.po 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 -trans.pt_BR = c-api/concrete.po -source_file = ../../pot/c-api/concrete.pot +[o:python-doc:p:python-313:r:c-api--concrete] +file_filter = c-api/concrete.po 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 -trans.pt_BR = c-api/contextvars.po -source_file = ../../pot/c-api/contextvars.pot +[o:python-doc:p:python-313:r:c-api--contextvars] +file_filter = c-api/contextvars.po 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 -trans.pt_BR = c-api/conversion.po -source_file = ../../pot/c-api/conversion.pot +[o:python-doc:p:python-313:r:c-api--conversion] +file_filter = c-api/conversion.po 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 -trans.pt_BR = c-api/coro.po -source_file = ../../pot/c-api/coro.pot +[o:python-doc:p:python-313:r:c-api--coro] +file_filter = c-api/coro.po 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 -trans.pt_BR = c-api/datetime.po -source_file = ../../pot/c-api/datetime.pot +[o:python-doc:p:python-313:r:c-api--curses] +file_filter = c-api/curses.po +type = PO +minimum_perc = 0 +resource_name = c-api--curses +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:c-api--datetime] +file_filter = c-api/datetime.po 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 -trans.pt_BR = c-api/descriptor.po -source_file = ../../pot/c-api/descriptor.pot +[o:python-doc:p:python-313:r:c-api--descriptor] +file_filter = c-api/descriptor.po 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 -trans.pt_BR = c-api/dict.po -source_file = ../../pot/c-api/dict.pot +[o:python-doc:p:python-313:r:c-api--dict] +file_filter = c-api/dict.po 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 -trans.pt_BR = c-api/exceptions.po -source_file = ../../pot/c-api/exceptions.pot +[o:python-doc:p:python-313:r:c-api--exceptions] +file_filter = c-api/exceptions.po 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 -trans.pt_BR = c-api/file.po -source_file = ../../pot/c-api/file.pot +[o:python-doc:p:python-313:r:c-api--file] +file_filter = c-api/file.po 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 -trans.pt_BR = c-api/float.po -source_file = ../../pot/c-api/float.pot +[o:python-doc:p:python-313:r:c-api--float] +file_filter = c-api/float.po 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 -trans.pt_BR = c-api/frame.po -source_file = ../../pot/c-api/frame.pot +[o:python-doc:p:python-313:r:c-api--frame] +file_filter = c-api/frame.po 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 -trans.pt_BR = c-api/function.po -source_file = ../../pot/c-api/function.pot +[o:python-doc:p:python-313:r:c-api--function] +file_filter = c-api/function.po 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 -trans.pt_BR = c-api/gcsupport.po -source_file = ../../pot/c-api/gcsupport.pot +[o:python-doc:p:python-313:r:c-api--gcsupport] +file_filter = c-api/gcsupport.po 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 -trans.pt_BR = c-api/gen.po -source_file = ../../pot/c-api/gen.pot +[o:python-doc:p:python-313:r:c-api--gen] +file_filter = c-api/gen.po 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 -trans.pt_BR = c-api/hash.po -source_file = ../../pot/c-api/hash.pot +[o:python-doc:p:python-313:r:c-api--hash] +file_filter = c-api/hash.po 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 -trans.pt_BR = c-api/import.po -source_file = ../../pot/c-api/import.pot +[o:python-doc:p:python-313:r:c-api--import] +file_filter = c-api/import.po 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 -trans.pt_BR = c-api/index.po -source_file = ../../pot/c-api/index.pot +[o:python-doc:p:python-313:r:c-api--index] +file_filter = c-api/index.po 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 -trans.pt_BR = c-api/init.po -source_file = ../../pot/c-api/init.pot +[o:python-doc:p:python-313:r:c-api--init] +file_filter = c-api/init.po 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 -trans.pt_BR = c-api/init_config.po -source_file = ../../pot/c-api/init_config.pot +[o:python-doc:p:python-313:r:c-api--init_config] +file_filter = c-api/init_config.po 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 -trans.pt_BR = c-api/intro.po -source_file = ../../pot/c-api/intro.pot +[o:python-doc:p:python-313:r:c-api--intro] +file_filter = c-api/intro.po 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 -trans.pt_BR = c-api/iter.po -source_file = ../../pot/c-api/iter.pot +[o:python-doc:p:python-313:r:c-api--iter] +file_filter = c-api/iter.po 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 -trans.pt_BR = c-api/iterator.po -source_file = ../../pot/c-api/iterator.pot +[o:python-doc:p:python-313:r:c-api--iterator] +file_filter = c-api/iterator.po 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 -trans.pt_BR = c-api/list.po -source_file = ../../pot/c-api/list.pot +[o:python-doc:p:python-313:r:c-api--list] +file_filter = c-api/list.po 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 -trans.pt_BR = c-api/long.po -source_file = ../../pot/c-api/long.pot +[o:python-doc:p:python-313:r:c-api--long] +file_filter = c-api/long.po 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 -trans.pt_BR = c-api/mapping.po -source_file = ../../pot/c-api/mapping.pot +[o:python-doc:p:python-313:r:c-api--mapping] +file_filter = c-api/mapping.po 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 -trans.pt_BR = c-api/marshal.po -source_file = ../../pot/c-api/marshal.pot +[o:python-doc:p:python-313:r:c-api--marshal] +file_filter = c-api/marshal.po 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 -trans.pt_BR = c-api/memory.po -source_file = ../../pot/c-api/memory.pot +[o:python-doc:p:python-313:r:c-api--memory] +file_filter = c-api/memory.po 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 -trans.pt_BR = c-api/memoryview.po -source_file = ../../pot/c-api/memoryview.pot +[o:python-doc:p:python-313:r:c-api--memoryview] +file_filter = c-api/memoryview.po 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 -trans.pt_BR = c-api/method.po -source_file = ../../pot/c-api/method.pot +[o:python-doc:p:python-313:r:c-api--method] +file_filter = c-api/method.po 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 -trans.pt_BR = c-api/module.po -source_file = ../../pot/c-api/module.pot +[o:python-doc:p:python-313:r:c-api--module] +file_filter = c-api/module.po 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 -trans.pt_BR = c-api/monitoring.po -source_file = ../../pot/c-api/monitoring.pot +[o:python-doc:p:python-313:r:c-api--monitoring] +file_filter = c-api/monitoring.po 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 -trans.pt_BR = c-api/none.po -source_file = ../../pot/c-api/none.pot +[o:python-doc:p:python-313:r:c-api--none] +file_filter = c-api/none.po 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 -trans.pt_BR = c-api/number.po -source_file = ../../pot/c-api/number.pot +[o:python-doc:p:python-313:r:c-api--number] +file_filter = c-api/number.po 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 -trans.pt_BR = c-api/object.po -source_file = ../../pot/c-api/object.pot +[o:python-doc:p:python-313:r:c-api--object] +file_filter = c-api/object.po 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 -trans.pt_BR = c-api/objimpl.po -source_file = ../../pot/c-api/objimpl.pot +[o:python-doc:p:python-313:r:c-api--objimpl] +file_filter = c-api/objimpl.po 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 -trans.pt_BR = c-api/perfmaps.po -source_file = ../../pot/c-api/perfmaps.pot +[o:python-doc:p:python-313:r:c-api--perfmaps] +file_filter = c-api/perfmaps.po 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 -trans.pt_BR = c-api/refcounting.po -source_file = ../../pot/c-api/refcounting.pot +[o:python-doc:p:python-313:r:c-api--refcounting] +file_filter = c-api/refcounting.po 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 -trans.pt_BR = c-api/reflection.po -source_file = ../../pot/c-api/reflection.pot +[o:python-doc:p:python-313:r:c-api--reflection] +file_filter = c-api/reflection.po 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 -trans.pt_BR = c-api/sequence.po -source_file = ../../pot/c-api/sequence.pot +[o:python-doc:p:python-313:r:c-api--sequence] +file_filter = c-api/sequence.po 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 -trans.pt_BR = c-api/set.po -source_file = ../../pot/c-api/set.pot +[o:python-doc:p:python-313:r:c-api--set] +file_filter = c-api/set.po 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 -trans.pt_BR = c-api/slice.po -source_file = ../../pot/c-api/slice.pot +[o:python-doc:p:python-313:r:c-api--slice] +file_filter = c-api/slice.po 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 -trans.pt_BR = c-api/stable.po -source_file = ../../pot/c-api/stable.pot +[o:python-doc:p:python-313:r:c-api--stable] +file_filter = c-api/stable.po 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 -trans.pt_BR = c-api/structures.po -source_file = ../../pot/c-api/structures.pot +[o:python-doc:p:python-313:r:c-api--structures] +file_filter = c-api/structures.po 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 -trans.pt_BR = c-api/sys.po -source_file = ../../pot/c-api/sys.pot +[o:python-doc:p:python-313:r:c-api--sys] +file_filter = c-api/sys.po 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 -trans.pt_BR = c-api/time.po -source_file = ../../pot/c-api/time.pot +[o:python-doc:p:python-313:r:c-api--time] +file_filter = c-api/time.po 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 -trans.pt_BR = c-api/tuple.po -source_file = ../../pot/c-api/tuple.pot +[o:python-doc:p:python-313:r:c-api--tuple] +file_filter = c-api/tuple.po 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 -trans.pt_BR = c-api/type.po -source_file = ../../pot/c-api/type.pot +[o:python-doc:p:python-313:r:c-api--type] +file_filter = c-api/type.po 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 -trans.pt_BR = c-api/typehints.po -source_file = ../../pot/c-api/typehints.pot +[o:python-doc:p:python-313:r:c-api--typehints] +file_filter = c-api/typehints.po 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 -trans.pt_BR = c-api/typeobj.po -source_file = ../../pot/c-api/typeobj.pot +[o:python-doc:p:python-313:r:c-api--typeobj] +file_filter = c-api/typeobj.po 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 -trans.pt_BR = c-api/unicode.po -source_file = ../../pot/c-api/unicode.pot +[o:python-doc:p:python-313:r:c-api--unicode] +file_filter = c-api/unicode.po 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 -trans.pt_BR = c-api/utilities.po -source_file = ../../pot/c-api/utilities.pot +[o:python-doc:p:python-313:r:c-api--utilities] +file_filter = c-api/utilities.po 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 -trans.pt_BR = c-api/veryhigh.po -source_file = ../../pot/c-api/veryhigh.pot +[o:python-doc:p:python-313:r:c-api--veryhigh] +file_filter = c-api/veryhigh.po 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 -trans.pt_BR = c-api/weakref.po -source_file = ../../pot/c-api/weakref.pot +[o:python-doc:p:python-313:r:c-api--weakref] +file_filter = c-api/weakref.po 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 -trans.pt_BR = contents.po -source_file = ../../pot/contents.pot +[o:python-doc:p:python-313:r:contents] +file_filter = contents.po 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 -trans.pt_BR = copyright.po -source_file = ../../pot/copyright.pot +[o:python-doc:p:python-313:r:copyright] +file_filter = copyright.po 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 -trans.pt_BR = deprecations/c-api-pending-removal-in-3.14.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-3.14.pot +[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 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 -trans.pt_BR = deprecations/c-api-pending-removal-in-3.15.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-3.15.pot +[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 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 -trans.pt_BR = deprecations/c-api-pending-removal-in-future.po -source_file = ../../pot/deprecations/c-api-pending-removal-in-future.pot +[o:python-doc:p:python-313:r:deprecations--c-api-pending-removal-in-3_16] +file_filter = deprecations/c-api-pending-removal-in-3.16.po +type = PO +minimum_perc = 0 +resource_name = deprecations--c-api-pending-removal-in-3_16 +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:deprecations--c-api-pending-removal-in-future] +file_filter = deprecations/c-api-pending-removal-in-future.po 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 -trans.pt_BR = deprecations/index.po -source_file = ../../pot/deprecations/index.pot +[o:python-doc:p:python-313:r:deprecations--index] +file_filter = deprecations/index.po 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 -trans.pt_BR = deprecations/pending-removal-in-3.13.po -source_file = ../../pot/deprecations/pending-removal-in-3.13.pot +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_13] +file_filter = deprecations/pending-removal-in-3.13.po 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 -trans.pt_BR = deprecations/pending-removal-in-3.14.po -source_file = ../../pot/deprecations/pending-removal-in-3.14.pot +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_14] +file_filter = deprecations/pending-removal-in-3.14.po 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 -trans.pt_BR = deprecations/pending-removal-in-3.15.po -source_file = ../../pot/deprecations/pending-removal-in-3.15.pot +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_15] +file_filter = deprecations/pending-removal-in-3.15.po 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 -trans.pt_BR = deprecations/pending-removal-in-3.16.po -source_file = ../../pot/deprecations/pending-removal-in-3.16.pot +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_16] +file_filter = deprecations/pending-removal-in-3.16.po 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 -trans.pt_BR = deprecations/pending-removal-in-future.po -source_file = ../../pot/deprecations/pending-removal-in-future.pot +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-3_17] +file_filter = deprecations/pending-removal-in-3.17.po +type = PO +minimum_perc = 0 +resource_name = deprecations--pending-removal-in-3_17 +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:deprecations--pending-removal-in-future] +file_filter = deprecations/pending-removal-in-future.po 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 -trans.pt_BR = distributing/index.po -source_file = ../../pot/distributing/index.pot +[o:python-doc:p:python-313:r:distributing--index] +file_filter = distributing/index.po 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 -trans.pt_BR = extending/building.po -source_file = ../../pot/extending/building.pot +[o:python-doc:p:python-313:r:extending--building] +file_filter = extending/building.po 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 -trans.pt_BR = extending/embedding.po -source_file = ../../pot/extending/embedding.pot +[o:python-doc:p:python-313:r:extending--embedding] +file_filter = extending/embedding.po 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 -trans.pt_BR = extending/extending.po -source_file = ../../pot/extending/extending.pot +[o:python-doc:p:python-313:r:extending--extending] +file_filter = extending/extending.po 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 -trans.pt_BR = extending/index.po -source_file = ../../pot/extending/index.pot +[o:python-doc:p:python-313:r:extending--index] +file_filter = extending/index.po 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 -trans.pt_BR = extending/newtypes.po -source_file = ../../pot/extending/newtypes.pot +[o:python-doc:p:python-313:r:extending--newtypes] +file_filter = extending/newtypes.po 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 -trans.pt_BR = extending/newtypes_tutorial.po -source_file = ../../pot/extending/newtypes_tutorial.pot +[o:python-doc:p:python-313:r:extending--newtypes_tutorial] +file_filter = extending/newtypes_tutorial.po 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 -trans.pt_BR = extending/windows.po -source_file = ../../pot/extending/windows.pot +[o:python-doc:p:python-313:r:extending--windows] +file_filter = extending/windows.po 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 -trans.pt_BR = faq/design.po -source_file = ../../pot/faq/design.pot +[o:python-doc:p:python-313:r:faq--design] +file_filter = faq/design.po 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 -trans.pt_BR = faq/extending.po -source_file = ../../pot/faq/extending.pot +[o:python-doc:p:python-313:r:faq--extending] +file_filter = faq/extending.po 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 -trans.pt_BR = faq/general.po -source_file = ../../pot/faq/general.pot +[o:python-doc:p:python-313:r:faq--general] +file_filter = faq/general.po 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 -trans.pt_BR = faq/gui.po -source_file = ../../pot/faq/gui.pot +[o:python-doc:p:python-313:r:faq--gui] +file_filter = faq/gui.po 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 -trans.pt_BR = faq/index.po -source_file = ../../pot/faq/index.pot +[o:python-doc:p:python-313:r:faq--index] +file_filter = faq/index.po 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 -trans.pt_BR = faq/installed.po -source_file = ../../pot/faq/installed.pot +[o:python-doc:p:python-313:r:faq--installed] +file_filter = faq/installed.po 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 -trans.pt_BR = faq/library.po -source_file = ../../pot/faq/library.pot +[o:python-doc:p:python-313:r:faq--library] +file_filter = faq/library.po 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 -trans.pt_BR = faq/programming.po -source_file = ../../pot/faq/programming.pot +[o:python-doc:p:python-313:r:faq--programming] +file_filter = faq/programming.po 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 -trans.pt_BR = faq/windows.po -source_file = ../../pot/faq/windows.pot +[o:python-doc:p:python-313:r:faq--windows] +file_filter = faq/windows.po 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 -trans.pt_BR = glossary.po -source_file = ../../pot/glossary.pot +[o:python-doc:p:python-313:r:glossary_] +file_filter = glossary.po 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 -trans.pt_BR = howto/annotations.po -source_file = ../../pot/howto/annotations.pot +[o:python-doc:p:python-313:r:howto--a-conceptual-overview-of-asyncio] +file_filter = howto/a-conceptual-overview-of-asyncio.po +type = PO +minimum_perc = 0 +resource_name = howto--a-conceptual-overview-of-asyncio +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:howto--annotations] +file_filter = howto/annotations.po 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 -trans.pt_BR = howto/argparse.po -source_file = ../../pot/howto/argparse.pot +[o:python-doc:p:python-313:r:howto--argparse] +file_filter = howto/argparse.po 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 -trans.pt_BR = howto/clinic.po -source_file = ../../pot/howto/clinic.pot +[o:python-doc:p:python-313:r:howto--argparse-optparse] +file_filter = howto/argparse-optparse.po +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 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 -trans.pt_BR = howto/cporting.po -source_file = ../../pot/howto/cporting.pot +[o:python-doc:p:python-313:r:howto--cporting] +file_filter = howto/cporting.po 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 -trans.pt_BR = howto/curses.po -source_file = ../../pot/howto/curses.pot +[o:python-doc:p:python-313:r:howto--curses] +file_filter = howto/curses.po 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 -trans.pt_BR = howto/descriptor.po -source_file = ../../pot/howto/descriptor.pot +[o:python-doc:p:python-313:r:howto--descriptor] +file_filter = howto/descriptor.po 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 -trans.pt_BR = howto/enum.po -source_file = ../../pot/howto/enum.pot +[o:python-doc:p:python-313:r:howto--enum] +file_filter = howto/enum.po 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 -trans.pt_BR = howto/free-threading-extensions.po -source_file = ../../pot/howto/free-threading-extensions.pot +[o:python-doc:p:python-313:r:howto--free-threading-extensions] +file_filter = howto/free-threading-extensions.po 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 -trans.pt_BR = howto/functional.po -source_file = ../../pot/howto/functional.pot +[o:python-doc:p:python-313:r:howto--free-threading-python] +file_filter = howto/free-threading-python.po +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 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 -trans.pt_BR = howto/gdb_helpers.po -source_file = ../../pot/howto/gdb_helpers.pot +[o:python-doc:p:python-313:r:howto--gdb_helpers] +file_filter = howto/gdb_helpers.po 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 -trans.pt_BR = howto/index.po -source_file = ../../pot/howto/index.pot +[o:python-doc:p:python-313:r:howto--index] +file_filter = howto/index.po 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 -trans.pt_BR = howto/instrumentation.po -source_file = ../../pot/howto/instrumentation.pot +[o:python-doc:p:python-313:r:howto--instrumentation] +file_filter = howto/instrumentation.po 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 -trans.pt_BR = howto/ipaddress.po -source_file = ../../pot/howto/ipaddress.pot +[o:python-doc:p:python-313:r:howto--ipaddress] +file_filter = howto/ipaddress.po 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 -trans.pt_BR = howto/isolating-extensions.po -source_file = ../../pot/howto/isolating-extensions.pot +[o:python-doc:p:python-313:r:howto--isolating-extensions] +file_filter = howto/isolating-extensions.po 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 -trans.pt_BR = howto/logging.po -source_file = ../../pot/howto/logging.pot +[o:python-doc:p:python-313:r:howto--logging] +file_filter = howto/logging.po 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 -trans.pt_BR = howto/logging-cookbook.po -source_file = ../../pot/howto/logging-cookbook.pot +[o:python-doc:p:python-313:r:howto--logging-cookbook] +file_filter = howto/logging-cookbook.po 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 -trans.pt_BR = howto/mro.po -source_file = ../../pot/howto/mro.pot +[o:python-doc:p:python-313:r:howto--mro] +file_filter = howto/mro.po 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 -trans.pt_BR = howto/perf_profiling.po -source_file = ../../pot/howto/perf_profiling.pot +[o:python-doc:p:python-313:r:howto--perf_profiling] +file_filter = howto/perf_profiling.po 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 -trans.pt_BR = howto/pyporting.po -source_file = ../../pot/howto/pyporting.pot +[o:python-doc:p:python-313:r:howto--pyporting] +file_filter = howto/pyporting.po 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 -trans.pt_BR = howto/regex.po -source_file = ../../pot/howto/regex.pot +[o:python-doc:p:python-313:r:howto--regex] +file_filter = howto/regex.po 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 -trans.pt_BR = howto/sockets.po -source_file = ../../pot/howto/sockets.pot +[o:python-doc:p:python-313:r:howto--sockets] +file_filter = howto/sockets.po 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 -trans.pt_BR = howto/sorting.po -source_file = ../../pot/howto/sorting.pot +[o:python-doc:p:python-313:r:howto--sorting] +file_filter = howto/sorting.po 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 -trans.pt_BR = howto/timerfd.po -source_file = ../../pot/howto/timerfd.pot +[o:python-doc:p:python-313:r:howto--timerfd] +file_filter = howto/timerfd.po 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 -trans.pt_BR = howto/unicode.po -source_file = ../../pot/howto/unicode.pot +[o:python-doc:p:python-313:r:howto--unicode] +file_filter = howto/unicode.po 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 -trans.pt_BR = howto/urllib2.po -source_file = ../../pot/howto/urllib2.pot +[o:python-doc:p:python-313:r:howto--urllib2] +file_filter = howto/urllib2.po 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 -trans.pt_BR = installing/index.po -source_file = ../../pot/installing/index.pot +[o:python-doc:p:python-313:r:installing--index] +file_filter = installing/index.po 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 -trans.pt_BR = library/__future__.po -source_file = ../../pot/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 -trans.pt_BR = library/__main__.po -source_file = ../../pot/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 -trans.pt_BR = library/_thread.po -source_file = ../../pot/library/_thread.pot +[o:python-doc:p:python-313:r:library--abc] +file_filter = library/abc.po type = PO minimum_perc = 0 -resource_name = library--_thread +resource_name = library--abc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--abc] -file_filter = .//LC_MESSAGES/library/abc.po -trans.pt_BR = library/abc.po -source_file = ../../pot/library/abc.pot +[o:python-doc:p:python-313:r:library--aifc] +file_filter = library/aifc.po type = PO minimum_perc = 0 -resource_name = library--abc +resource_name = library--aifc replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--allos] -file_filter = .//LC_MESSAGES/library/allos.po -trans.pt_BR = library/allos.po -source_file = ../../pot/library/allos.pot +[o:python-doc:p:python-313:r:library--allos] +file_filter = library/allos.po 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 -trans.pt_BR = library/archiving.po -source_file = ../../pot/library/archiving.pot +[o:python-doc:p:python-313:r:library--archiving] +file_filter = library/archiving.po 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 -trans.pt_BR = library/argparse.po -source_file = ../../pot/library/argparse.pot +[o:python-doc:p:python-313:r:library--argparse] +file_filter = library/argparse.po 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 -trans.pt_BR = library/array.po -source_file = ../../pot/library/array.pot +[o:python-doc:p:python-313:r:library--array] +file_filter = library/array.po 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 -trans.pt_BR = library/ast.po -source_file = ../../pot/library/ast.pot +[o:python-doc:p:python-313:r:library--ast] +file_filter = library/ast.po 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 -trans.pt_BR = library/asyncio.po -source_file = ../../pot/library/asyncio.pot +[o:python-doc:p:python-313:r:library--asynchat] +file_filter = library/asynchat.po +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 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 -trans.pt_BR = library/asyncio-api-index.po -source_file = ../../pot/library/asyncio-api-index.pot +[o:python-doc:p:python-313:r:library--asyncio-api-index] +file_filter = library/asyncio-api-index.po 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 -trans.pt_BR = library/asyncio-dev.po -source_file = ../../pot/library/asyncio-dev.pot +[o:python-doc:p:python-313:r:library--asyncio-dev] +file_filter = library/asyncio-dev.po 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 -trans.pt_BR = library/asyncio-eventloop.po -source_file = ../../pot/library/asyncio-eventloop.pot +[o:python-doc:p:python-313:r:library--asyncio-eventloop] +file_filter = library/asyncio-eventloop.po 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 -trans.pt_BR = library/asyncio-exceptions.po -source_file = ../../pot/library/asyncio-exceptions.pot +[o:python-doc:p:python-313:r:library--asyncio-exceptions] +file_filter = library/asyncio-exceptions.po 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 -trans.pt_BR = library/asyncio-extending.po -source_file = ../../pot/library/asyncio-extending.pot +[o:python-doc:p:python-313:r:library--asyncio-extending] +file_filter = library/asyncio-extending.po 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 -trans.pt_BR = library/asyncio-future.po -source_file = ../../pot/library/asyncio-future.pot +[o:python-doc:p:python-313:r:library--asyncio-future] +file_filter = library/asyncio-future.po 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 -trans.pt_BR = library/asyncio-llapi-index.po -source_file = ../../pot/library/asyncio-llapi-index.pot +[o:python-doc:p:python-313:r:library--asyncio-llapi-index] +file_filter = library/asyncio-llapi-index.po 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 -trans.pt_BR = library/asyncio-platforms.po -source_file = ../../pot/library/asyncio-platforms.pot +[o:python-doc:p:python-313:r:library--asyncio-platforms] +file_filter = library/asyncio-platforms.po 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 -trans.pt_BR = library/asyncio-policy.po -source_file = ../../pot/library/asyncio-policy.pot +[o:python-doc:p:python-313:r:library--asyncio-policy] +file_filter = library/asyncio-policy.po 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 -trans.pt_BR = library/asyncio-protocol.po -source_file = ../../pot/library/asyncio-protocol.pot +[o:python-doc:p:python-313:r:library--asyncio-protocol] +file_filter = library/asyncio-protocol.po 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 -trans.pt_BR = library/asyncio-queue.po -source_file = ../../pot/library/asyncio-queue.pot +[o:python-doc:p:python-313:r:library--asyncio-queue] +file_filter = library/asyncio-queue.po 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 -trans.pt_BR = library/asyncio-runner.po -source_file = ../../pot/library/asyncio-runner.pot +[o:python-doc:p:python-313:r:library--asyncio-runner] +file_filter = library/asyncio-runner.po 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 -trans.pt_BR = library/asyncio-stream.po -source_file = ../../pot/library/asyncio-stream.pot +[o:python-doc:p:python-313:r:library--asyncio-stream] +file_filter = library/asyncio-stream.po 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 -trans.pt_BR = library/asyncio-subprocess.po -source_file = ../../pot/library/asyncio-subprocess.pot +[o:python-doc:p:python-313:r:library--asyncio-subprocess] +file_filter = library/asyncio-subprocess.po 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 -trans.pt_BR = library/asyncio-sync.po -source_file = ../../pot/library/asyncio-sync.pot +[o:python-doc:p:python-313:r:library--asyncio-sync] +file_filter = library/asyncio-sync.po 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 -trans.pt_BR = library/asyncio-task.po -source_file = ../../pot/library/asyncio-task.pot +[o:python-doc:p:python-313:r:library--asyncio-task] +file_filter = library/asyncio-task.po 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 -trans.pt_BR = library/atexit.po -source_file = ../../pot/library/atexit.pot +[o:python-doc:p:python-313:r:library--asyncore] +file_filter = library/asyncore.po +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 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 -trans.pt_BR = library/audit_events.po -source_file = ../../pot/library/audit_events.pot +[o:python-doc:p:python-313:r:library--audioop] +file_filter = library/audioop.po +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 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 -trans.pt_BR = library/base64.po -source_file = ../../pot/library/base64.pot +[o:python-doc:p:python-313:r:library--base64] +file_filter = library/base64.po 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 -trans.pt_BR = library/bdb.po -source_file = ../../pot/library/bdb.pot +[o:python-doc:p:python-313:r:library--bdb] +file_filter = library/bdb.po 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 -trans.pt_BR = library/binary.po -source_file = ../../pot/library/binary.pot +[o:python-doc:p:python-313:r:library--binary] +file_filter = library/binary.po 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 -trans.pt_BR = library/binascii.po -source_file = ../../pot/library/binascii.pot +[o:python-doc:p:python-313:r:library--binascii] +file_filter = library/binascii.po 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 -trans.pt_BR = library/bisect.po -source_file = ../../pot/library/bisect.pot +[o:python-doc:p:python-313:r:library--bisect] +file_filter = library/bisect.po 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 -trans.pt_BR = library/builtins.po -source_file = ../../pot/library/builtins.pot +[o:python-doc:p:python-313:r:library--builtins] +file_filter = library/builtins.po 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 -trans.pt_BR = library/bz2.po -source_file = ../../pot/library/bz2.pot +[o:python-doc:p:python-313:r:library--bz2] +file_filter = library/bz2.po 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 -trans.pt_BR = library/calendar.po -source_file = ../../pot/library/calendar.pot +[o:python-doc:p:python-313:r:library--calendar] +file_filter = library/calendar.po 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 -trans.pt_BR = library/cmath.po -source_file = ../../pot/library/cmath.pot +[o:python-doc:p:python-313:r:library--cgi] +file_filter = library/cgi.po +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 +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 +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 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 -trans.pt_BR = library/cmd.po -source_file = ../../pot/library/cmd.pot +[o:python-doc:p:python-313:r:library--cmd] +file_filter = library/cmd.po 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 -trans.pt_BR = library/cmdline.po -source_file = ../../pot/library/cmdline.pot +[o:python-doc:p:python-313:r:library--cmdline] +file_filter = library/cmdline.po 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 -trans.pt_BR = library/code.po -source_file = ../../pot/library/code.pot +[o:python-doc:p:python-313:r:library--cmdlinelibs] +file_filter = library/cmdlinelibs.po +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 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 -trans.pt_BR = library/codecs.po -source_file = ../../pot/library/codecs.pot +[o:python-doc:p:python-313:r:library--codecs] +file_filter = library/codecs.po 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 -trans.pt_BR = library/codeop.po -source_file = ../../pot/library/codeop.pot +[o:python-doc:p:python-313:r:library--codeop] +file_filter = library/codeop.po 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 -trans.pt_BR = library/collections.po -source_file = ../../pot/library/collections.pot +[o:python-doc:p:python-313:r:library--collections] +file_filter = library/collections.po 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 -trans.pt_BR = library/collections.abc.po -source_file = ../../pot/library/collections.abc.pot +[o:python-doc:p:python-313:r:library--collections_abc] +file_filter = library/collections.abc.po 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 -trans.pt_BR = library/colorsys.po -source_file = ../../pot/library/colorsys.pot +[o:python-doc:p:python-313:r:library--colorsys] +file_filter = library/colorsys.po 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 -trans.pt_BR = library/compileall.po -source_file = ../../pot/library/compileall.pot +[o:python-doc:p:python-313:r:library--compileall] +file_filter = library/compileall.po 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 -trans.pt_BR = library/concurrency.po -source_file = ../../pot/library/concurrency.pot +[o:python-doc:p:python-313:r:library--concurrency] +file_filter = library/concurrency.po 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 -trans.pt_BR = library/concurrent.po -source_file = ../../pot/library/concurrent.pot +[o:python-doc:p:python-313:r:library--concurrent] +file_filter = library/concurrent.po 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 -trans.pt_BR = library/concurrent.futures.po -source_file = ../../pot/library/concurrent.futures.pot +[o:python-doc:p:python-313:r:library--concurrent_futures] +file_filter = library/concurrent.futures.po 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 -trans.pt_BR = library/configparser.po -source_file = ../../pot/library/configparser.pot +[o:python-doc:p:python-313:r:library--configparser] +file_filter = library/configparser.po 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 -trans.pt_BR = library/constants.po -source_file = ../../pot/library/constants.pot +[o:python-doc:p:python-313:r:library--constants] +file_filter = library/constants.po 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 -trans.pt_BR = library/contextlib.po -source_file = ../../pot/library/contextlib.pot +[o:python-doc:p:python-313:r:library--contextlib] +file_filter = library/contextlib.po 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 -trans.pt_BR = library/contextvars.po -source_file = ../../pot/library/contextvars.pot +[o:python-doc:p:python-313:r:library--contextvars] +file_filter = library/contextvars.po 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 -trans.pt_BR = library/copy.po -source_file = ../../pot/library/copy.pot +[o:python-doc:p:python-313:r:library--copy] +file_filter = library/copy.po 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 -trans.pt_BR = library/copyreg.po -source_file = ../../pot/library/copyreg.pot +[o:python-doc:p:python-313:r:library--copyreg] +file_filter = library/copyreg.po 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 -trans.pt_BR = library/crypto.po -source_file = ../../pot/library/crypto.pot +[o:python-doc:p:python-313:r:library--crypt] +file_filter = library/crypt.po +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 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 -trans.pt_BR = library/csv.po -source_file = ../../pot/library/csv.pot +[o:python-doc:p:python-313:r:library--csv] +file_filter = library/csv.po 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 -trans.pt_BR = library/ctypes.po -source_file = ../../pot/library/ctypes.pot +[o:python-doc:p:python-313:r:library--ctypes] +file_filter = library/ctypes.po 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 -trans.pt_BR = library/curses.po -source_file = ../../pot/library/curses.pot +[o:python-doc:p:python-313:r:library--curses] +file_filter = library/curses.po 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 -trans.pt_BR = library/curses.ascii.po -source_file = ../../pot/library/curses.ascii.pot +[o:python-doc:p:python-313:r:library--curses_ascii] +file_filter = library/curses.ascii.po 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 -trans.pt_BR = library/curses.panel.po -source_file = ../../pot/library/curses.panel.pot +[o:python-doc:p:python-313:r:library--curses_panel] +file_filter = library/curses.panel.po 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 -trans.pt_BR = library/custominterp.po -source_file = ../../pot/library/custominterp.pot +[o:python-doc:p:python-313:r:library--custominterp] +file_filter = library/custominterp.po 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 -trans.pt_BR = library/dataclasses.po -source_file = ../../pot/library/dataclasses.pot +[o:python-doc:p:python-313:r:library--dataclasses] +file_filter = library/dataclasses.po 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 -trans.pt_BR = library/datatypes.po -source_file = ../../pot/library/datatypes.pot +[o:python-doc:p:python-313:r:library--datatypes] +file_filter = library/datatypes.po 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 -trans.pt_BR = library/datetime.po -source_file = ../../pot/library/datetime.pot +[o:python-doc:p:python-313:r:library--datetime] +file_filter = library/datetime.po 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 -trans.pt_BR = library/dbm.po -source_file = ../../pot/library/dbm.pot +[o:python-doc:p:python-313:r:library--dbm] +file_filter = library/dbm.po 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 -trans.pt_BR = library/debug.po -source_file = ../../pot/library/debug.pot +[o:python-doc:p:python-313:r:library--debug] +file_filter = library/debug.po 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 -trans.pt_BR = library/decimal.po -source_file = ../../pot/library/decimal.pot +[o:python-doc:p:python-313:r:library--decimal] +file_filter = library/decimal.po 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 -trans.pt_BR = library/development.po -source_file = ../../pot/library/development.pot +[o:python-doc:p:python-313:r:library--development] +file_filter = library/development.po 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 -trans.pt_BR = library/devmode.po -source_file = ../../pot/library/devmode.pot +[o:python-doc:p:python-313:r:library--devmode] +file_filter = library/devmode.po 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 -trans.pt_BR = library/dialog.po -source_file = ../../pot/library/dialog.pot +[o:python-doc:p:python-313:r:library--dialog] +file_filter = library/dialog.po 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 -trans.pt_BR = library/difflib.po -source_file = ../../pot/library/difflib.pot +[o:python-doc:p:python-313:r:library--difflib] +file_filter = library/difflib.po 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 -trans.pt_BR = library/dis.po -source_file = ../../pot/library/dis.pot +[o:python-doc:p:python-313:r:library--dis] +file_filter = library/dis.po 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 -trans.pt_BR = library/distribution.po -source_file = ../../pot/library/distribution.pot +[o:python-doc:p:python-313:r:library--distribution] +file_filter = library/distribution.po 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 -trans.pt_BR = library/doctest.po -source_file = ../../pot/library/doctest.pot +[o:python-doc:p:python-313:r:library--distutils] +file_filter = library/distutils.po +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 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 -trans.pt_BR = library/email.po -source_file = ../../pot/library/email.pot +[o:python-doc:p:python-313:r:library--email] +file_filter = library/email.po 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 -trans.pt_BR = library/email.charset.po -source_file = ../../pot/library/email.charset.pot +[o:python-doc:p:python-313:r:library--email_charset] +file_filter = library/email.charset.po 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 -trans.pt_BR = library/email.compat32-message.po -source_file = ../../pot/library/email.compat32-message.pot +[o:python-doc:p:python-313:r:library--email_compat32-message] +file_filter = library/email.compat32-message.po 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 -trans.pt_BR = library/email.contentmanager.po -source_file = ../../pot/library/email.contentmanager.pot +[o:python-doc:p:python-313:r:library--email_contentmanager] +file_filter = library/email.contentmanager.po 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 -trans.pt_BR = library/email.encoders.po -source_file = ../../pot/library/email.encoders.pot +[o:python-doc:p:python-313:r:library--email_encoders] +file_filter = library/email.encoders.po 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 -trans.pt_BR = library/email.errors.po -source_file = ../../pot/library/email.errors.pot +[o:python-doc:p:python-313:r:library--email_errors] +file_filter = library/email.errors.po 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 -trans.pt_BR = library/email.examples.po -source_file = ../../pot/library/email.examples.pot +[o:python-doc:p:python-313:r:library--email_examples] +file_filter = library/email.examples.po 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 -trans.pt_BR = library/email.generator.po -source_file = ../../pot/library/email.generator.pot +[o:python-doc:p:python-313:r:library--email_generator] +file_filter = library/email.generator.po 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 -trans.pt_BR = library/email.header.po -source_file = ../../pot/library/email.header.pot +[o:python-doc:p:python-313:r:library--email_header] +file_filter = library/email.header.po 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 -trans.pt_BR = library/email.headerregistry.po -source_file = ../../pot/library/email.headerregistry.pot +[o:python-doc:p:python-313:r:library--email_headerregistry] +file_filter = library/email.headerregistry.po 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 -trans.pt_BR = library/email.iterators.po -source_file = ../../pot/library/email.iterators.pot +[o:python-doc:p:python-313:r:library--email_iterators] +file_filter = library/email.iterators.po 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 -trans.pt_BR = library/email.message.po -source_file = ../../pot/library/email.message.pot +[o:python-doc:p:python-313:r:library--email_message] +file_filter = library/email.message.po 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 -trans.pt_BR = library/email.mime.po -source_file = ../../pot/library/email.mime.pot +[o:python-doc:p:python-313:r:library--email_mime] +file_filter = library/email.mime.po 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 -trans.pt_BR = library/email.parser.po -source_file = ../../pot/library/email.parser.pot +[o:python-doc:p:python-313:r:library--email_parser] +file_filter = library/email.parser.po 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 -trans.pt_BR = library/email.policy.po -source_file = ../../pot/library/email.policy.pot +[o:python-doc:p:python-313:r:library--email_policy] +file_filter = library/email.policy.po 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 -trans.pt_BR = library/email.utils.po -source_file = ../../pot/library/email.utils.pot +[o:python-doc:p:python-313:r:library--email_utils] +file_filter = library/email.utils.po 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 -trans.pt_BR = library/ensurepip.po -source_file = ../../pot/library/ensurepip.pot +[o:python-doc:p:python-313:r:library--ensurepip] +file_filter = library/ensurepip.po 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 -trans.pt_BR = library/enum.po -source_file = ../../pot/library/enum.pot +[o:python-doc:p:python-313:r:library--enum] +file_filter = library/enum.po 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 -trans.pt_BR = library/errno.po -source_file = ../../pot/library/errno.pot +[o:python-doc:p:python-313:r:library--errno] +file_filter = library/errno.po 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 -trans.pt_BR = library/exceptions.po -source_file = ../../pot/library/exceptions.pot +[o:python-doc:p:python-313:r:library--exceptions] +file_filter = library/exceptions.po 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 -trans.pt_BR = library/faulthandler.po -source_file = ../../pot/library/faulthandler.pot +[o:python-doc:p:python-313:r:library--faulthandler] +file_filter = library/faulthandler.po 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 -trans.pt_BR = library/fcntl.po -source_file = ../../pot/library/fcntl.pot +[o:python-doc:p:python-313:r:library--fcntl] +file_filter = library/fcntl.po 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 -trans.pt_BR = library/filecmp.po -source_file = ../../pot/library/filecmp.pot +[o:python-doc:p:python-313:r:library--filecmp] +file_filter = library/filecmp.po 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 -trans.pt_BR = library/fileformats.po -source_file = ../../pot/library/fileformats.pot +[o:python-doc:p:python-313:r:library--fileformats] +file_filter = library/fileformats.po 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 -trans.pt_BR = library/fileinput.po -source_file = ../../pot/library/fileinput.pot +[o:python-doc:p:python-313:r:library--fileinput] +file_filter = library/fileinput.po 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 -trans.pt_BR = library/filesys.po -source_file = ../../pot/library/filesys.pot +[o:python-doc:p:python-313:r:library--filesys] +file_filter = library/filesys.po 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 -trans.pt_BR = library/fnmatch.po -source_file = ../../pot/library/fnmatch.pot +[o:python-doc:p:python-313:r:library--fnmatch] +file_filter = library/fnmatch.po 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 -trans.pt_BR = library/fractions.po -source_file = ../../pot/library/fractions.pot +[o:python-doc:p:python-313:r:library--fractions] +file_filter = library/fractions.po 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 -trans.pt_BR = library/frameworks.po -source_file = ../../pot/library/frameworks.pot +[o:python-doc:p:python-313:r:library--frameworks] +file_filter = library/frameworks.po 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 -trans.pt_BR = library/ftplib.po -source_file = ../../pot/library/ftplib.pot +[o:python-doc:p:python-313:r:library--ftplib] +file_filter = library/ftplib.po 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 -trans.pt_BR = library/functional.po -source_file = ../../pot/library/functional.pot +[o:python-doc:p:python-313:r:library--functional] +file_filter = library/functional.po 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 -trans.pt_BR = library/functions.po -source_file = ../../pot/library/functions.pot +[o:python-doc:p:python-313:r:library--functions] +file_filter = library/functions.po 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 -trans.pt_BR = library/functools.po -source_file = ../../pot/library/functools.pot +[o:python-doc:p:python-313:r:library--functools] +file_filter = library/functools.po 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 -trans.pt_BR = library/gc.po -source_file = ../../pot/library/gc.pot +[o:python-doc:p:python-313:r:library--__future__] +file_filter = library/__future__.po +type = PO +minimum_perc = 0 +resource_name = library--__future__ +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--gc] +file_filter = library/gc.po 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 -trans.pt_BR = library/getopt.po -source_file = ../../pot/library/getopt.pot +[o:python-doc:p:python-313:r:library--getopt] +file_filter = library/getopt.po 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 -trans.pt_BR = library/getpass.po -source_file = ../../pot/library/getpass.pot +[o:python-doc:p:python-313:r:library--getpass] +file_filter = library/getpass.po 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 -trans.pt_BR = library/gettext.po -source_file = ../../pot/library/gettext.pot +[o:python-doc:p:python-313:r:library--gettext] +file_filter = library/gettext.po 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 -trans.pt_BR = library/glob.po -source_file = ../../pot/library/glob.pot +[o:python-doc:p:python-313:r:library--glob] +file_filter = library/glob.po 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 -trans.pt_BR = library/graphlib.po -source_file = ../../pot/library/graphlib.pot +[o:python-doc:p:python-313:r:library--graphlib] +file_filter = library/graphlib.po 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 -trans.pt_BR = library/grp.po -source_file = ../../pot/library/grp.pot +[o:python-doc:p:python-313:r:library--grp] +file_filter = library/grp.po 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 -trans.pt_BR = library/gzip.po -source_file = ../../pot/library/gzip.pot +[o:python-doc:p:python-313:r:library--gzip] +file_filter = library/gzip.po 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 -trans.pt_BR = library/hashlib.po -source_file = ../../pot/library/hashlib.pot +[o:python-doc:p:python-313:r:library--hashlib] +file_filter = library/hashlib.po 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 -trans.pt_BR = library/heapq.po -source_file = ../../pot/library/heapq.pot +[o:python-doc:p:python-313:r:library--heapq] +file_filter = library/heapq.po 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 -trans.pt_BR = library/hmac.po -source_file = ../../pot/library/hmac.pot +[o:python-doc:p:python-313:r:library--hmac] +file_filter = library/hmac.po 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 -trans.pt_BR = library/html.po -source_file = ../../pot/library/html.pot +[o:python-doc:p:python-313:r:library--html] +file_filter = library/html.po 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 -trans.pt_BR = library/html.entities.po -source_file = ../../pot/library/html.entities.pot +[o:python-doc:p:python-313:r:library--html_entities] +file_filter = library/html.entities.po 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 -trans.pt_BR = library/html.parser.po -source_file = ../../pot/library/html.parser.pot +[o:python-doc:p:python-313:r:library--html_parser] +file_filter = library/html.parser.po 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 -trans.pt_BR = library/http.po -source_file = ../../pot/library/http.pot +[o:python-doc:p:python-313:r:library--http] +file_filter = library/http.po 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 -trans.pt_BR = library/http.client.po -source_file = ../../pot/library/http.client.pot +[o:python-doc:p:python-313:r:library--http_client] +file_filter = library/http.client.po 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 -trans.pt_BR = library/http.cookiejar.po -source_file = ../../pot/library/http.cookiejar.pot +[o:python-doc:p:python-313:r:library--http_cookiejar] +file_filter = library/http.cookiejar.po 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 -trans.pt_BR = library/http.cookies.po -source_file = ../../pot/library/http.cookies.pot +[o:python-doc:p:python-313:r:library--http_cookies] +file_filter = library/http.cookies.po 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 -trans.pt_BR = library/http.server.po -source_file = ../../pot/library/http.server.pot +[o:python-doc:p:python-313:r:library--http_server] +file_filter = library/http.server.po 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 -trans.pt_BR = library/i18n.po -source_file = ../../pot/library/i18n.pot +[o:python-doc:p:python-313:r:library--i18n] +file_filter = library/i18n.po 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 -trans.pt_BR = library/idle.po -source_file = ../../pot/library/idle.pot +[o:python-doc:p:python-313:r:library--idle] +file_filter = library/idle.po 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 -trans.pt_BR = library/imaplib.po -source_file = ../../pot/library/imaplib.pot +[o:python-doc:p:python-313:r:library--imaplib] +file_filter = library/imaplib.po 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 -trans.pt_BR = library/importlib.po -source_file = ../../pot/library/importlib.pot +[o:python-doc:p:python-313:r:library--imghdr] +file_filter = library/imghdr.po +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 +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 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 -trans.pt_BR = library/importlib.metadata.po -source_file = ../../pot/library/importlib.metadata.pot +[o:python-doc:p:python-313:r:library--importlib_metadata] +file_filter = library/importlib.metadata.po 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 -trans.pt_BR = library/importlib.resources.po -source_file = ../../pot/library/importlib.resources.pot +[o:python-doc:p:python-313:r:library--importlib_resources] +file_filter = library/importlib.resources.po 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 -trans.pt_BR = library/importlib.resources.abc.po -source_file = ../../pot/library/importlib.resources.abc.pot +[o:python-doc:p:python-313:r:library--importlib_resources_abc] +file_filter = library/importlib.resources.abc.po 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 -trans.pt_BR = library/index.po -source_file = ../../pot/library/index.pot +[o:python-doc:p:python-313:r:library--index] +file_filter = library/index.po 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 -trans.pt_BR = library/inspect.po -source_file = ../../pot/library/inspect.pot +[o:python-doc:p:python-313:r:library--inspect] +file_filter = library/inspect.po 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 -trans.pt_BR = library/internet.po -source_file = ../../pot/library/internet.pot +[o:python-doc:p:python-313:r:library--internet] +file_filter = library/internet.po 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 -trans.pt_BR = library/intro.po -source_file = ../../pot/library/intro.pot +[o:python-doc:p:python-313:r:library--intro] +file_filter = library/intro.po 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 -trans.pt_BR = library/io.po -source_file = ../../pot/library/io.pot +[o:python-doc:p:python-313:r:library--io] +file_filter = library/io.po 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 -trans.pt_BR = library/ipaddress.po -source_file = ../../pot/library/ipaddress.pot +[o:python-doc:p:python-313:r:library--ipaddress] +file_filter = library/ipaddress.po 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 -trans.pt_BR = library/ipc.po -source_file = ../../pot/library/ipc.pot +[o:python-doc:p:python-313:r:library--ipc] +file_filter = library/ipc.po 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 -trans.pt_BR = library/itertools.po -source_file = ../../pot/library/itertools.pot +[o:python-doc:p:python-313:r:library--itertools] +file_filter = library/itertools.po 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 -trans.pt_BR = library/json.po -source_file = ../../pot/library/json.pot +[o:python-doc:p:python-313:r:library--json] +file_filter = library/json.po 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 -trans.pt_BR = library/keyword.po -source_file = ../../pot/library/keyword.pot +[o:python-doc:p:python-313:r:library--keyword] +file_filter = library/keyword.po 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 -trans.pt_BR = library/language.po -source_file = ../../pot/library/language.pot +[o:python-doc:p:python-313:r:library--language] +file_filter = library/language.po 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 -trans.pt_BR = library/linecache.po -source_file = ../../pot/library/linecache.pot +[o:python-doc:p:python-313:r:library--linecache] +file_filter = library/linecache.po 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 -trans.pt_BR = library/locale.po -source_file = ../../pot/library/locale.pot +[o:python-doc:p:python-313:r:library--locale] +file_filter = library/locale.po 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 -trans.pt_BR = library/logging.po -source_file = ../../pot/library/logging.pot +[o:python-doc:p:python-313:r:library--logging] +file_filter = library/logging.po 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 -trans.pt_BR = library/logging.config.po -source_file = ../../pot/library/logging.config.pot +[o:python-doc:p:python-313:r:library--logging_config] +file_filter = library/logging.config.po 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 -trans.pt_BR = library/logging.handlers.po -source_file = ../../pot/library/logging.handlers.pot +[o:python-doc:p:python-313:r:library--logging_handlers] +file_filter = library/logging.handlers.po 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 -trans.pt_BR = library/lzma.po -source_file = ../../pot/library/lzma.pot +[o:python-doc:p:python-313:r:library--lzma] +file_filter = library/lzma.po 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 -trans.pt_BR = library/mailbox.po -source_file = ../../pot/library/mailbox.pot +[o:python-doc:p:python-313:r:library--mailbox] +file_filter = library/mailbox.po 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 -trans.pt_BR = library/markup.po -source_file = ../../pot/library/markup.pot +[o:python-doc:p:python-313:r:library--mailcap] +file_filter = library/mailcap.po +type = PO +minimum_perc = 0 +resource_name = library--mailcap +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--__main__] +file_filter = library/__main__.po +type = PO +minimum_perc = 0 +resource_name = library--__main__ +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--markup] +file_filter = library/markup.po 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 -trans.pt_BR = library/marshal.po -source_file = ../../pot/library/marshal.pot +[o:python-doc:p:python-313:r:library--marshal] +file_filter = library/marshal.po 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 -trans.pt_BR = library/math.po -source_file = ../../pot/library/math.pot +[o:python-doc:p:python-313:r:library--math] +file_filter = library/math.po 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 -trans.pt_BR = library/mimetypes.po -source_file = ../../pot/library/mimetypes.pot +[o:python-doc:p:python-313:r:library--mimetypes] +file_filter = library/mimetypes.po 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 -trans.pt_BR = library/mm.po -source_file = ../../pot/library/mm.pot +[o:python-doc:p:python-313:r:library--mm] +file_filter = library/mm.po 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 -trans.pt_BR = library/mmap.po -source_file = ../../pot/library/mmap.pot +[o:python-doc:p:python-313:r:library--mmap] +file_filter = library/mmap.po 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 -trans.pt_BR = library/modulefinder.po -source_file = ../../pot/library/modulefinder.pot +[o:python-doc:p:python-313:r:library--modulefinder] +file_filter = library/modulefinder.po 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 -trans.pt_BR = library/modules.po -source_file = ../../pot/library/modules.pot +[o:python-doc:p:python-313:r:library--modules] +file_filter = library/modules.po 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 -trans.pt_BR = library/msvcrt.po -source_file = ../../pot/library/msvcrt.pot +[o:python-doc:p:python-313:r:library--msilib] +file_filter = library/msilib.po +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 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 -trans.pt_BR = library/multiprocessing.po -source_file = ../../pot/library/multiprocessing.pot +[o:python-doc:p:python-313:r:library--multiprocessing] +file_filter = library/multiprocessing.po 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 -trans.pt_BR = library/multiprocessing.shared_memory.po -source_file = ../../pot/library/multiprocessing.shared_memory.pot +[o:python-doc:p:python-313:r:library--multiprocessing_shared_memory] +file_filter = library/multiprocessing.shared_memory.po 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 -trans.pt_BR = library/netdata.po -source_file = ../../pot/library/netdata.pot +[o:python-doc:p:python-313:r:library--netdata] +file_filter = library/netdata.po 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 -trans.pt_BR = library/netrc.po -source_file = ../../pot/library/netrc.pot +[o:python-doc:p:python-313:r:library--netrc] +file_filter = library/netrc.po 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 -trans.pt_BR = library/numbers.po -source_file = ../../pot/library/numbers.pot +[o:python-doc:p:python-313:r:library--nis] +file_filter = library/nis.po +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 +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 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 -trans.pt_BR = library/numeric.po -source_file = ../../pot/library/numeric.pot +[o:python-doc:p:python-313:r:library--numeric] +file_filter = library/numeric.po 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 -trans.pt_BR = library/operator.po -source_file = ../../pot/library/operator.pot +[o:python-doc:p:python-313:r:library--operator] +file_filter = library/operator.po 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 -trans.pt_BR = library/optparse.po -source_file = ../../pot/library/optparse.pot +[o:python-doc:p:python-313:r:library--optparse] +file_filter = library/optparse.po 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 -trans.pt_BR = library/os.po -source_file = ../../pot/library/os.pot +[o:python-doc:p:python-313:r:library--os] +file_filter = library/os.po 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 -trans.pt_BR = library/os.path.po -source_file = ../../pot/library/os.path.pot +[o:python-doc:p:python-313:r:library--os_path] +file_filter = library/os.path.po 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 -trans.pt_BR = library/pathlib.po -source_file = ../../pot/library/pathlib.pot +[o:python-doc:p:python-313:r:library--ossaudiodev] +file_filter = library/ossaudiodev.po +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 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 -trans.pt_BR = library/pdb.po -source_file = ../../pot/library/pdb.pot +[o:python-doc:p:python-313:r:library--pdb] +file_filter = library/pdb.po 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 -trans.pt_BR = library/persistence.po -source_file = ../../pot/library/persistence.pot +[o:python-doc:p:python-313:r:library--persistence] +file_filter = library/persistence.po 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 -trans.pt_BR = library/pickle.po -source_file = ../../pot/library/pickle.pot +[o:python-doc:p:python-313:r:library--pickle] +file_filter = library/pickle.po 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 -trans.pt_BR = library/pickletools.po -source_file = ../../pot/library/pickletools.pot +[o:python-doc:p:python-313:r:library--pickletools] +file_filter = library/pickletools.po 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 -trans.pt_BR = library/pkgutil.po -source_file = ../../pot/library/pkgutil.pot +[o:python-doc:p:python-313:r:library--pipes] +file_filter = library/pipes.po +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 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 -trans.pt_BR = library/platform.po -source_file = ../../pot/library/platform.pot +[o:python-doc:p:python-313:r:library--platform] +file_filter = library/platform.po 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 -trans.pt_BR = library/plistlib.po -source_file = ../../pot/library/plistlib.pot +[o:python-doc:p:python-313:r:library--plistlib] +file_filter = library/plistlib.po 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 -trans.pt_BR = library/poplib.po -source_file = ../../pot/library/poplib.pot +[o:python-doc:p:python-313:r:library--poplib] +file_filter = library/poplib.po 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 -trans.pt_BR = library/posix.po -source_file = ../../pot/library/posix.pot +[o:python-doc:p:python-313:r:library--posix] +file_filter = library/posix.po 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 -trans.pt_BR = library/pprint.po -source_file = ../../pot/library/pprint.pot +[o:python-doc:p:python-313:r:library--pprint] +file_filter = library/pprint.po 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 -trans.pt_BR = library/profile.po -source_file = ../../pot/library/profile.pot +[o:python-doc:p:python-313:r:library--profile] +file_filter = library/profile.po 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 -trans.pt_BR = library/pty.po -source_file = ../../pot/library/pty.pot +[o:python-doc:p:python-313:r:library--pty] +file_filter = library/pty.po 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 -trans.pt_BR = library/pwd.po -source_file = ../../pot/library/pwd.pot +[o:python-doc:p:python-313:r:library--pwd] +file_filter = library/pwd.po 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 -trans.pt_BR = library/py_compile.po -source_file = ../../pot/library/py_compile.pot +[o:python-doc:p:python-313:r:library--pyclbr] +file_filter = library/pyclbr.po type = PO minimum_perc = 0 -resource_name = library--py_compile +resource_name = library--pyclbr replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pyclbr] -file_filter = .//LC_MESSAGES/library/pyclbr.po -trans.pt_BR = library/pyclbr.po -source_file = ../../pot/library/pyclbr.pot +[o:python-doc:p:python-313:r:library--py_compile] +file_filter = library/py_compile.po type = PO minimum_perc = 0 -resource_name = library--pyclbr +resource_name = library--py_compile replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--pydoc] -file_filter = .//LC_MESSAGES/library/pydoc.po -trans.pt_BR = library/pydoc.po -source_file = ../../pot/library/pydoc.pot +[o:python-doc:p:python-313:r:library--pydoc] +file_filter = library/pydoc.po 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 -trans.pt_BR = library/pyexpat.po -source_file = ../../pot/library/pyexpat.pot +[o:python-doc:p:python-313:r:library--pyexpat] +file_filter = library/pyexpat.po 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 -trans.pt_BR = library/python.po -source_file = ../../pot/library/python.pot +[o:python-doc:p:python-313:r:library--python] +file_filter = library/python.po 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 -trans.pt_BR = library/queue.po -source_file = ../../pot/library/queue.pot +[o:python-doc:p:python-313:r:library--queue] +file_filter = library/queue.po 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 -trans.pt_BR = library/quopri.po -source_file = ../../pot/library/quopri.pot +[o:python-doc:p:python-313:r:library--quopri] +file_filter = library/quopri.po 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 -trans.pt_BR = library/random.po -source_file = ../../pot/library/random.pot +[o:python-doc:p:python-313:r:library--random] +file_filter = library/random.po 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 -trans.pt_BR = library/re.po -source_file = ../../pot/library/re.pot +[o:python-doc:p:python-313:r:library--re] +file_filter = library/re.po 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 -trans.pt_BR = library/readline.po -source_file = ../../pot/library/readline.pot +[o:python-doc:p:python-313:r:library--readline] +file_filter = library/readline.po 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 -trans.pt_BR = library/reprlib.po -source_file = ../../pot/library/reprlib.pot +[o:python-doc:p:python-313:r:library--removed] +file_filter = library/removed.po +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 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 -trans.pt_BR = library/resource.po -source_file = ../../pot/library/resource.pot +[o:python-doc:p:python-313:r:library--resource] +file_filter = library/resource.po 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 -trans.pt_BR = library/rlcompleter.po -source_file = ../../pot/library/rlcompleter.pot +[o:python-doc:p:python-313:r:library--rlcompleter] +file_filter = library/rlcompleter.po 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 -trans.pt_BR = library/runpy.po -source_file = ../../pot/library/runpy.pot +[o:python-doc:p:python-313:r:library--runpy] +file_filter = library/runpy.po 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 -trans.pt_BR = library/sched.po -source_file = ../../pot/library/sched.pot +[o:python-doc:p:python-313:r:library--sched] +file_filter = library/sched.po 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 -trans.pt_BR = library/secrets.po -source_file = ../../pot/library/secrets.pot +[o:python-doc:p:python-313:r:library--secrets] +file_filter = library/secrets.po 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 -trans.pt_BR = library/security_warnings.po -source_file = ../../pot/library/security_warnings.pot +[o:python-doc:p:python-313:r:library--security_warnings] +file_filter = library/security_warnings.po 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 -trans.pt_BR = library/select.po -source_file = ../../pot/library/select.pot +[o:python-doc:p:python-313:r:library--select] +file_filter = library/select.po 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 -trans.pt_BR = library/selectors.po -source_file = ../../pot/library/selectors.pot +[o:python-doc:p:python-313:r:library--selectors] +file_filter = library/selectors.po 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 -trans.pt_BR = library/shelve.po -source_file = ../../pot/library/shelve.pot +[o:python-doc:p:python-313:r:library--shelve] +file_filter = library/shelve.po 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 -trans.pt_BR = library/shlex.po -source_file = ../../pot/library/shlex.pot +[o:python-doc:p:python-313:r:library--shlex] +file_filter = library/shlex.po 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 -trans.pt_BR = library/shutil.po -source_file = ../../pot/library/shutil.pot +[o:python-doc:p:python-313:r:library--shutil] +file_filter = library/shutil.po 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 -trans.pt_BR = library/signal.po -source_file = ../../pot/library/signal.pot +[o:python-doc:p:python-313:r:library--signal] +file_filter = library/signal.po 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 -trans.pt_BR = library/site.po -source_file = ../../pot/library/site.pot +[o:python-doc:p:python-313:r:library--site] +file_filter = library/site.po 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 -trans.pt_BR = library/smtplib.po -source_file = ../../pot/library/smtplib.pot +[o:python-doc:p:python-313:r:library--smtpd] +file_filter = library/smtpd.po +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 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 -trans.pt_BR = library/socket.po -source_file = ../../pot/library/socket.pot +[o:python-doc:p:python-313:r:library--sndhdr] +file_filter = library/sndhdr.po +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 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 -trans.pt_BR = library/socketserver.po -source_file = ../../pot/library/socketserver.pot +[o:python-doc:p:python-313:r:library--socketserver] +file_filter = library/socketserver.po 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 -trans.pt_BR = library/sqlite3.po -source_file = ../../pot/library/sqlite3.pot +[o:python-doc:p:python-313:r:library--spwd] +file_filter = library/spwd.po +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 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 -trans.pt_BR = library/ssl.po -source_file = ../../pot/library/ssl.pot +[o:python-doc:p:python-313:r:library--ssl] +file_filter = library/ssl.po 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 -trans.pt_BR = library/stat.po -source_file = ../../pot/library/stat.pot +[o:python-doc:p:python-313:r:library--stat] +file_filter = library/stat.po 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 -trans.pt_BR = library/statistics.po -source_file = ../../pot/library/statistics.pot +[o:python-doc:p:python-313:r:library--statistics] +file_filter = library/statistics.po 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 -trans.pt_BR = library/stdtypes.po -source_file = ../../pot/library/stdtypes.pot +[o:python-doc:p:python-313:r:library--stdtypes] +file_filter = library/stdtypes.po 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 -trans.pt_BR = library/string.po -source_file = ../../pot/library/string.pot +[o:python-doc:p:python-313:r:library--string] +file_filter = library/string.po 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 -trans.pt_BR = library/stringprep.po -source_file = ../../pot/library/stringprep.pot +[o:python-doc:p:python-313:r:library--stringprep] +file_filter = library/stringprep.po 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 -trans.pt_BR = library/struct.po -source_file = ../../pot/library/struct.pot +[o:python-doc:p:python-313:r:library--struct] +file_filter = library/struct.po 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 -trans.pt_BR = library/subprocess.po -source_file = ../../pot/library/subprocess.pot +[o:python-doc:p:python-313:r:library--subprocess] +file_filter = library/subprocess.po 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 -trans.pt_BR = library/superseded.po -source_file = ../../pot/library/superseded.pot +[o:python-doc:p:python-313:r:library--sunau] +file_filter = library/sunau.po +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 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 -trans.pt_BR = library/symtable.po -source_file = ../../pot/library/symtable.pot +[o:python-doc:p:python-313:r:library--symtable] +file_filter = library/symtable.po 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 -trans.pt_BR = library/sys.po -source_file = ../../pot/library/sys.pot +[o:python-doc:p:python-313:r:library--sys] +file_filter = library/sys.po 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 -trans.pt_BR = library/sys.monitoring.po -source_file = ../../pot/library/sys.monitoring.pot +[o:python-doc:p:python-313:r:library--sysconfig] +file_filter = library/sysconfig.po type = PO minimum_perc = 0 -resource_name = library--sys_monitoring +resource_name = library--sysconfig 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 -trans.pt_BR = library/sys_path_init.po -source_file = ../../pot/library/sys_path_init.pot +[o:python-doc:p:python-313:r:library--syslog] +file_filter = library/syslog.po type = PO minimum_perc = 0 -resource_name = library--sys_path_init +resource_name = library--syslog replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--sysconfig] -file_filter = .//LC_MESSAGES/library/sysconfig.po -trans.pt_BR = library/sysconfig.po -source_file = ../../pot/library/sysconfig.pot +[o:python-doc:p:python-313:r:library--sys_monitoring] +file_filter = library/sys.monitoring.po type = PO minimum_perc = 0 -resource_name = library--sysconfig +resource_name = library--sys_monitoring replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--syslog] -file_filter = .//LC_MESSAGES/library/syslog.po -trans.pt_BR = library/syslog.po -source_file = ../../pot/library/syslog.pot +[o:python-doc:p:python-313:r:library--sys_path_init] +file_filter = library/sys_path_init.po type = PO minimum_perc = 0 -resource_name = library--syslog +resource_name = library--sys_path_init replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--tabnanny] -file_filter = .//LC_MESSAGES/library/tabnanny.po -trans.pt_BR = library/tabnanny.po -source_file = ../../pot/library/tabnanny.pot +[o:python-doc:p:python-313:r:library--tabnanny] +file_filter = library/tabnanny.po 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 -trans.pt_BR = library/tarfile.po -source_file = ../../pot/library/tarfile.pot +[o:python-doc:p:python-313:r:library--tarfile] +file_filter = library/tarfile.po 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 -trans.pt_BR = library/tempfile.po -source_file = ../../pot/library/tempfile.pot +[o:python-doc:p:python-313:r:library--telnetlib] +file_filter = library/telnetlib.po +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 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 -trans.pt_BR = library/termios.po -source_file = ../../pot/library/termios.pot +[o:python-doc:p:python-313:r:library--termios] +file_filter = library/termios.po 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 -trans.pt_BR = library/test.po -source_file = ../../pot/library/test.pot +[o:python-doc:p:python-313:r:library--test] +file_filter = library/test.po 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 -trans.pt_BR = library/text.po -source_file = ../../pot/library/text.pot +[o:python-doc:p:python-313:r:library--text] +file_filter = library/text.po 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 -trans.pt_BR = library/textwrap.po -source_file = ../../pot/library/textwrap.pot +[o:python-doc:p:python-313:r:library--textwrap] +file_filter = library/textwrap.po 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 -trans.pt_BR = library/threading.po -source_file = ../../pot/library/threading.pot +[o:python-doc:p:python-313:r:library--_thread] +file_filter = library/_thread.po +type = PO +minimum_perc = 0 +resource_name = library--_thread +replace_edited_strings = false +keep_translations = false + +[o:python-doc:p:python-313:r:library--threading] +file_filter = library/threading.po 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 -trans.pt_BR = library/time.po -source_file = ../../pot/library/time.pot +[o:python-doc:p:python-313:r:library--time] +file_filter = library/time.po 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 -trans.pt_BR = library/timeit.po -source_file = ../../pot/library/timeit.pot +[o:python-doc:p:python-313:r:library--timeit] +file_filter = library/timeit.po 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 -trans.pt_BR = library/tk.po -source_file = ../../pot/library/tk.pot +[o:python-doc:p:python-313:r:library--tk] +file_filter = library/tk.po 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 -trans.pt_BR = library/tkinter.po -source_file = ../../pot/library/tkinter.pot +[o:python-doc:p:python-313:r:library--tkinter] +file_filter = library/tkinter.po 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 -trans.pt_BR = library/tkinter.colorchooser.po -source_file = ../../pot/library/tkinter.colorchooser.pot +[o:python-doc:p:python-313:r:library--tkinter_colorchooser] +file_filter = library/tkinter.colorchooser.po 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 -trans.pt_BR = library/tkinter.dnd.po -source_file = ../../pot/library/tkinter.dnd.pot +[o:python-doc:p:python-313:r:library--tkinter_dnd] +file_filter = library/tkinter.dnd.po 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 -trans.pt_BR = library/tkinter.font.po -source_file = ../../pot/library/tkinter.font.pot +[o:python-doc:p:python-313:r:library--tkinter_font] +file_filter = library/tkinter.font.po 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 -trans.pt_BR = library/tkinter.messagebox.po -source_file = ../../pot/library/tkinter.messagebox.pot +[o:python-doc:p:python-313:r:library--tkinter_messagebox] +file_filter = library/tkinter.messagebox.po 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 -trans.pt_BR = library/tkinter.scrolledtext.po -source_file = ../../pot/library/tkinter.scrolledtext.pot +[o:python-doc:p:python-313:r:library--tkinter_scrolledtext] +file_filter = library/tkinter.scrolledtext.po 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 -trans.pt_BR = library/tkinter.ttk.po -source_file = ../../pot/library/tkinter.ttk.pot +[o:python-doc:p:python-313:r:library--tkinter_ttk] +file_filter = library/tkinter.ttk.po 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 -trans.pt_BR = library/token.po -source_file = ../../pot/library/token.pot +[o:python-doc:p:python-313:r:library--token] +file_filter = library/token.po 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 -trans.pt_BR = library/tokenize.po -source_file = ../../pot/library/tokenize.pot +[o:python-doc:p:python-313:r:library--tokenize] +file_filter = library/tokenize.po 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 -trans.pt_BR = library/tomllib.po -source_file = ../../pot/library/tomllib.pot +[o:python-doc:p:python-313:r:library--tomllib] +file_filter = library/tomllib.po 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 -trans.pt_BR = library/trace.po -source_file = ../../pot/library/trace.pot +[o:python-doc:p:python-313:r:library--trace] +file_filter = library/trace.po 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 -trans.pt_BR = library/traceback.po -source_file = ../../pot/library/traceback.pot +[o:python-doc:p:python-313:r:library--traceback] +file_filter = library/traceback.po 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 -trans.pt_BR = library/tracemalloc.po -source_file = ../../pot/library/tracemalloc.pot +[o:python-doc:p:python-313:r:library--tracemalloc] +file_filter = library/tracemalloc.po 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 -trans.pt_BR = library/tty.po -source_file = ../../pot/library/tty.pot +[o:python-doc:p:python-313:r:library--tty] +file_filter = library/tty.po 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 -trans.pt_BR = library/turtle.po -source_file = ../../pot/library/turtle.pot +[o:python-doc:p:python-313:r:library--turtle] +file_filter = library/turtle.po 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 -trans.pt_BR = library/types.po -source_file = ../../pot/library/types.pot +[o:python-doc:p:python-313:r:library--types] +file_filter = library/types.po 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 -trans.pt_BR = library/typing.po -source_file = ../../pot/library/typing.pot +[o:python-doc:p:python-313:r:library--typing] +file_filter = library/typing.po 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 -trans.pt_BR = library/unicodedata.po -source_file = ../../pot/library/unicodedata.pot +[o:python-doc:p:python-313:r:library--unicodedata] +file_filter = library/unicodedata.po 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 -trans.pt_BR = library/unittest.po -source_file = ../../pot/library/unittest.pot +[o:python-doc:p:python-313:r:library--unittest] +file_filter = library/unittest.po 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 -trans.pt_BR = library/unittest.mock.po -source_file = ../../pot/library/unittest.mock.pot +[o:python-doc:p:python-313:r:library--unittest_mock] +file_filter = library/unittest.mock.po 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 -trans.pt_BR = library/unittest.mock-examples.po -source_file = ../../pot/library/unittest.mock-examples.pot +[o:python-doc:p:python-313:r:library--unittest_mock-examples] +file_filter = library/unittest.mock-examples.po 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 -trans.pt_BR = library/unix.po -source_file = ../../pot/library/unix.pot +[o:python-doc:p:python-313:r:library--unix] +file_filter = library/unix.po 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 -trans.pt_BR = library/urllib.po -source_file = ../../pot/library/urllib.pot +[o:python-doc:p:python-313:r:library--urllib] +file_filter = library/urllib.po 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 -trans.pt_BR = library/urllib.error.po -source_file = ../../pot/library/urllib.error.pot +[o:python-doc:p:python-313:r:library--urllib_error] +file_filter = library/urllib.error.po 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 -trans.pt_BR = library/urllib.parse.po -source_file = ../../pot/library/urllib.parse.pot +[o:python-doc:p:python-313:r:library--urllib_parse] +file_filter = library/urllib.parse.po 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 -trans.pt_BR = library/urllib.request.po -source_file = ../../pot/library/urllib.request.pot +[o:python-doc:p:python-313:r:library--urllib_request] +file_filter = library/urllib.request.po 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 -trans.pt_BR = library/urllib.robotparser.po -source_file = ../../pot/library/urllib.robotparser.pot +[o:python-doc:p:python-313:r:library--urllib_robotparser] +file_filter = library/urllib.robotparser.po 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 -trans.pt_BR = library/uuid.po -source_file = ../../pot/library/uuid.pot +[o:python-doc:p:python-313:r:library--uu] +file_filter = library/uu.po +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 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 -trans.pt_BR = library/venv.po -source_file = ../../pot/library/venv.pot +[o:python-doc:p:python-313:r:library--venv] +file_filter = library/venv.po 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 -trans.pt_BR = library/warnings.po -source_file = ../../pot/library/warnings.pot +[o:python-doc:p:python-313:r:library--warnings] +file_filter = library/warnings.po 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 -trans.pt_BR = library/wave.po -source_file = ../../pot/library/wave.pot +[o:python-doc:p:python-313:r:library--wave] +file_filter = library/wave.po 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 -trans.pt_BR = library/weakref.po -source_file = ../../pot/library/weakref.pot +[o:python-doc:p:python-313:r:library--weakref] +file_filter = library/weakref.po 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 -trans.pt_BR = library/webbrowser.po -source_file = ../../pot/library/webbrowser.pot +[o:python-doc:p:python-313:r:library--webbrowser] +file_filter = library/webbrowser.po 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 -trans.pt_BR = library/windows.po -source_file = ../../pot/library/windows.pot +[o:python-doc:p:python-313:r:library--windows] +file_filter = library/windows.po 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 -trans.pt_BR = library/winreg.po -source_file = ../../pot/library/winreg.pot +[o:python-doc:p:python-313:r:library--winreg] +file_filter = library/winreg.po 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 -trans.pt_BR = library/winsound.po -source_file = ../../pot/library/winsound.pot +[o:python-doc:p:python-313:r:library--winsound] +file_filter = library/winsound.po 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 -trans.pt_BR = library/wsgiref.po -source_file = ../../pot/library/wsgiref.pot +[o:python-doc:p:python-313:r:library--wsgiref] +file_filter = library/wsgiref.po 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 -trans.pt_BR = library/xml.po -source_file = ../../pot/library/xml.pot +[o:python-doc:p:python-313:r:library--xdrlib] +file_filter = library/xdrlib.po +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 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 -trans.pt_BR = library/xml.dom.po -source_file = ../../pot/library/xml.dom.pot +[o:python-doc:p:python-313:r:library--xml_dom] +file_filter = library/xml.dom.po 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 -trans.pt_BR = library/xml.dom.minidom.po -source_file = ../../pot/library/xml.dom.minidom.pot +[o:python-doc:p:python-313:r:library--xml_dom_minidom] +file_filter = library/xml.dom.minidom.po 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 -trans.pt_BR = library/xml.dom.pulldom.po -source_file = ../../pot/library/xml.dom.pulldom.pot +[o:python-doc:p:python-313:r:library--xml_dom_pulldom] +file_filter = library/xml.dom.pulldom.po 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 -trans.pt_BR = library/xml.etree.elementtree.po -source_file = ../../pot/library/xml.etree.elementtree.pot +[o:python-doc:p:python-313:r:library--xml_etree_elementtree] +file_filter = library/xml.etree.elementtree.po 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 -trans.pt_BR = library/xml.sax.po -source_file = ../../pot/library/xml.sax.pot +[o:python-doc:p:python-313:r:library--xmlrpc] +file_filter = library/xmlrpc.po type = PO minimum_perc = 0 -resource_name = library--xml_sax +resource_name = library--xmlrpc 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 -trans.pt_BR = library/xml.sax.handler.po -source_file = ../../pot/library/xml.sax.handler.pot +[o:python-doc:p:python-313:r:library--xmlrpc_client] +file_filter = library/xmlrpc.client.po type = PO minimum_perc = 0 -resource_name = library--xml_sax_handler +resource_name = library--xmlrpc_client 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 -trans.pt_BR = library/xml.sax.reader.po -source_file = ../../pot/library/xml.sax.reader.pot +[o:python-doc:p:python-313:r:library--xmlrpc_server] +file_filter = library/xmlrpc.server.po type = PO minimum_perc = 0 -resource_name = library--xml_sax_reader +resource_name = library--xmlrpc_server 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 -trans.pt_BR = library/xml.sax.utils.po -source_file = ../../pot/library/xml.sax.utils.pot +[o:python-doc:p:python-313:r:library--xml_sax] +file_filter = library/xml.sax.po type = PO minimum_perc = 0 -resource_name = library--xml_sax_utils +resource_name = library--xml_sax replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--xmlrpc] -file_filter = .//LC_MESSAGES/library/xmlrpc.po -trans.pt_BR = library/xmlrpc.po -source_file = ../../pot/library/xmlrpc.pot +[o:python-doc:p:python-313:r:library--xml_sax_handler] +file_filter = library/xml.sax.handler.po type = PO minimum_perc = 0 -resource_name = library--xmlrpc +resource_name = library--xml_sax_handler 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 -trans.pt_BR = library/xmlrpc.client.po -source_file = ../../pot/library/xmlrpc.client.pot +[o:python-doc:p:python-313:r:library--xml_sax_reader] +file_filter = library/xml.sax.reader.po type = PO minimum_perc = 0 -resource_name = library--xmlrpc_client +resource_name = library--xml_sax_reader 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 -trans.pt_BR = library/xmlrpc.server.po -source_file = ../../pot/library/xmlrpc.server.pot +[o:python-doc:p:python-313:r:library--xml_sax_utils] +file_filter = library/xml.sax.utils.po type = PO minimum_perc = 0 -resource_name = library--xmlrpc_server +resource_name = library--xml_sax_utils replace_edited_strings = false keep_translations = false -[o:python-doc:p:python-newest:r:library--zipapp] -file_filter = .//LC_MESSAGES/library/zipapp.po -trans.pt_BR = library/zipapp.po -source_file = ../../pot/library/zipapp.pot +[o:python-doc:p:python-313:r:library--zipapp] +file_filter = library/zipapp.po 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 -trans.pt_BR = library/zipfile.po -source_file = ../../pot/library/zipfile.pot +[o:python-doc:p:python-313:r:library--zipfile] +file_filter = library/zipfile.po 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 -trans.pt_BR = library/zipimport.po -source_file = ../../pot/library/zipimport.pot +[o:python-doc:p:python-313:r:library--zipimport] +file_filter = library/zipimport.po 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 -trans.pt_BR = library/zlib.po -source_file = ../../pot/library/zlib.pot +[o:python-doc:p:python-313:r:library--zlib] +file_filter = library/zlib.po 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 -trans.pt_BR = library/zoneinfo.po -source_file = ../../pot/library/zoneinfo.pot +[o:python-doc:p:python-313:r:library--zoneinfo] +file_filter = library/zoneinfo.po 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 -trans.pt_BR = license.po -source_file = ../../pot/license.pot +[o:python-doc:p:python-313:r:license] +file_filter = license.po 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 -trans.pt_BR = reference/compound_stmts.po -source_file = ../../pot/reference/compound_stmts.pot +[o:python-doc:p:python-313:r:reference--compound_stmts] +file_filter = reference/compound_stmts.po 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 -trans.pt_BR = reference/datamodel.po -source_file = ../../pot/reference/datamodel.pot +[o:python-doc:p:python-313:r:reference--datamodel] +file_filter = reference/datamodel.po 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 -trans.pt_BR = reference/executionmodel.po -source_file = ../../pot/reference/executionmodel.pot +[o:python-doc:p:python-313:r:reference--executionmodel] +file_filter = reference/executionmodel.po 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 -trans.pt_BR = reference/expressions.po -source_file = ../../pot/reference/expressions.pot +[o:python-doc:p:python-313:r:reference--expressions] +file_filter = reference/expressions.po 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 -trans.pt_BR = reference/grammar.po -source_file = ../../pot/reference/grammar.pot +[o:python-doc:p:python-313:r:reference--grammar] +file_filter = reference/grammar.po 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 -trans.pt_BR = reference/import.po -source_file = ../../pot/reference/import.pot +[o:python-doc:p:python-313:r:reference--import] +file_filter = reference/import.po 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 -trans.pt_BR = reference/index.po -source_file = ../../pot/reference/index.pot +[o:python-doc:p:python-313:r:reference--index] +file_filter = reference/index.po 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 -trans.pt_BR = reference/introduction.po -source_file = ../../pot/reference/introduction.pot +[o:python-doc:p:python-313:r:reference--introduction] +file_filter = reference/introduction.po 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 -trans.pt_BR = reference/lexical_analysis.po -source_file = ../../pot/reference/lexical_analysis.pot +[o:python-doc:p:python-313:r:reference--lexical_analysis] +file_filter = reference/lexical_analysis.po 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 -trans.pt_BR = reference/simple_stmts.po -source_file = ../../pot/reference/simple_stmts.pot +[o:python-doc:p:python-313:r:reference--simple_stmts] +file_filter = reference/simple_stmts.po 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 -trans.pt_BR = reference/toplevel_components.po -source_file = ../../pot/reference/toplevel_components.pot +[o:python-doc:p:python-313:r:reference--toplevel_components] +file_filter = reference/toplevel_components.po 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 -trans.pt_BR = sphinx.po -source_file = ../../pot/sphinx.pot +[o:python-doc:p:python-313:r:sphinx] +file_filter = sphinx.po 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 -trans.pt_BR = tutorial/appendix.po -source_file = ../../pot/tutorial/appendix.pot +[o:python-doc:p:python-313:r:tutorial--appendix] +file_filter = tutorial/appendix.po 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 -trans.pt_BR = tutorial/appetite.po -source_file = ../../pot/tutorial/appetite.pot +[o:python-doc:p:python-313:r:tutorial--appetite] +file_filter = tutorial/appetite.po 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 -trans.pt_BR = tutorial/classes.po -source_file = ../../pot/tutorial/classes.pot +[o:python-doc:p:python-313:r:tutorial--classes] +file_filter = tutorial/classes.po 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 -trans.pt_BR = tutorial/controlflow.po -source_file = ../../pot/tutorial/controlflow.pot +[o:python-doc:p:python-313:r:tutorial--controlflow] +file_filter = tutorial/controlflow.po 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 -trans.pt_BR = tutorial/datastructures.po -source_file = ../../pot/tutorial/datastructures.pot +[o:python-doc:p:python-313:r:tutorial--datastructures] +file_filter = tutorial/datastructures.po 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 -trans.pt_BR = tutorial/errors.po -source_file = ../../pot/tutorial/errors.pot +[o:python-doc:p:python-313:r:tutorial--errors] +file_filter = tutorial/errors.po 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 -trans.pt_BR = tutorial/floatingpoint.po -source_file = ../../pot/tutorial/floatingpoint.pot +[o:python-doc:p:python-313:r:tutorial--floatingpoint] +file_filter = tutorial/floatingpoint.po 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 -trans.pt_BR = tutorial/index.po -source_file = ../../pot/tutorial/index.pot +[o:python-doc:p:python-313:r:tutorial--index] +file_filter = tutorial/index.po 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 -trans.pt_BR = tutorial/inputoutput.po -source_file = ../../pot/tutorial/inputoutput.pot +[o:python-doc:p:python-313:r:tutorial--inputoutput] +file_filter = tutorial/inputoutput.po 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 -trans.pt_BR = tutorial/interactive.po -source_file = ../../pot/tutorial/interactive.pot +[o:python-doc:p:python-313:r:tutorial--interactive] +file_filter = tutorial/interactive.po 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 -trans.pt_BR = tutorial/interpreter.po -source_file = ../../pot/tutorial/interpreter.pot +[o:python-doc:p:python-313:r:tutorial--interpreter] +file_filter = tutorial/interpreter.po 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 -trans.pt_BR = tutorial/introduction.po -source_file = ../../pot/tutorial/introduction.pot +[o:python-doc:p:python-313:r:tutorial--introduction] +file_filter = tutorial/introduction.po 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 -trans.pt_BR = tutorial/modules.po -source_file = ../../pot/tutorial/modules.pot +[o:python-doc:p:python-313:r:tutorial--modules] +file_filter = tutorial/modules.po 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 -trans.pt_BR = tutorial/stdlib.po -source_file = ../../pot/tutorial/stdlib.pot +[o:python-doc:p:python-313:r:tutorial--stdlib] +file_filter = tutorial/stdlib.po 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 -trans.pt_BR = tutorial/stdlib2.po -source_file = ../../pot/tutorial/stdlib2.pot +[o:python-doc:p:python-313:r:tutorial--stdlib2] +file_filter = tutorial/stdlib2.po 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 -trans.pt_BR = tutorial/venv.po -source_file = ../../pot/tutorial/venv.pot +[o:python-doc:p:python-313:r:tutorial--venv] +file_filter = tutorial/venv.po 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 -trans.pt_BR = tutorial/whatnow.po -source_file = ../../pot/tutorial/whatnow.pot +[o:python-doc:p:python-313:r:tutorial--whatnow] +file_filter = tutorial/whatnow.po 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 -trans.pt_BR = using/cmdline.po -source_file = ../../pot/using/cmdline.pot +[o:python-doc:p:python-313:r:using--android] +file_filter = using/android.po +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 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 -trans.pt_BR = using/configure.po -source_file = ../../pot/using/configure.pot +[o:python-doc:p:python-313:r:using--configure] +file_filter = using/configure.po 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 -trans.pt_BR = using/editors.po -source_file = ../../pot/using/editors.pot +[o:python-doc:p:python-313:r:using--editors] +file_filter = using/editors.po 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 -trans.pt_BR = using/index.po -source_file = ../../pot/using/index.pot +[o:python-doc:p:python-313:r:using--index] +file_filter = using/index.po 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 -trans.pt_BR = using/ios.po -source_file = ../../pot/using/ios.pot +[o:python-doc:p:python-313:r:using--ios] +file_filter = using/ios.po 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 -trans.pt_BR = using/mac.po -source_file = ../../pot/using/mac.pot +[o:python-doc:p:python-313:r:using--mac] +file_filter = using/mac.po 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 -trans.pt_BR = using/unix.po -source_file = ../../pot/using/unix.pot +[o:python-doc:p:python-313:r:using--unix] +file_filter = using/unix.po 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 -trans.pt_BR = using/windows.po -source_file = ../../pot/using/windows.pot +[o:python-doc:p:python-313:r:using--windows] +file_filter = using/windows.po 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 -trans.pt_BR = whatsnew/2.0.po -source_file = ../../pot/whatsnew/2.0.pot +[o:python-doc:p:python-313:r:whatsnew--2_0] +file_filter = whatsnew/2.0.po 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 -trans.pt_BR = whatsnew/2.1.po -source_file = ../../pot/whatsnew/2.1.pot +[o:python-doc:p:python-313:r:whatsnew--2_1] +file_filter = whatsnew/2.1.po 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 -trans.pt_BR = whatsnew/2.2.po -source_file = ../../pot/whatsnew/2.2.pot +[o:python-doc:p:python-313:r:whatsnew--2_2] +file_filter = whatsnew/2.2.po 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 -trans.pt_BR = whatsnew/2.3.po -source_file = ../../pot/whatsnew/2.3.pot +[o:python-doc:p:python-313:r:whatsnew--2_3] +file_filter = whatsnew/2.3.po 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 -trans.pt_BR = whatsnew/2.4.po -source_file = ../../pot/whatsnew/2.4.pot +[o:python-doc:p:python-313:r:whatsnew--2_4] +file_filter = whatsnew/2.4.po 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 -trans.pt_BR = whatsnew/2.5.po -source_file = ../../pot/whatsnew/2.5.pot +[o:python-doc:p:python-313:r:whatsnew--2_5] +file_filter = whatsnew/2.5.po 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 -trans.pt_BR = whatsnew/2.6.po -source_file = ../../pot/whatsnew/2.6.pot +[o:python-doc:p:python-313:r:whatsnew--2_6] +file_filter = whatsnew/2.6.po 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 -trans.pt_BR = whatsnew/2.7.po -source_file = ../../pot/whatsnew/2.7.pot +[o:python-doc:p:python-313:r:whatsnew--2_7] +file_filter = whatsnew/2.7.po 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 -trans.pt_BR = whatsnew/3.0.po -source_file = ../../pot/whatsnew/3.0.pot +[o:python-doc:p:python-313:r:whatsnew--3_0] +file_filter = whatsnew/3.0.po 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 -trans.pt_BR = whatsnew/3.1.po -source_file = ../../pot/whatsnew/3.1.pot +[o:python-doc:p:python-313:r:whatsnew--3_1] +file_filter = whatsnew/3.1.po 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 -trans.pt_BR = whatsnew/3.10.po -source_file = ../../pot/whatsnew/3.10.pot +[o:python-doc:p:python-313:r:whatsnew--3_10] +file_filter = whatsnew/3.10.po 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 -trans.pt_BR = whatsnew/3.11.po -source_file = ../../pot/whatsnew/3.11.pot +[o:python-doc:p:python-313:r:whatsnew--3_11] +file_filter = whatsnew/3.11.po 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 -trans.pt_BR = whatsnew/3.12.po -source_file = ../../pot/whatsnew/3.12.pot +[o:python-doc:p:python-313:r:whatsnew--3_12] +file_filter = whatsnew/3.12.po 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 -trans.pt_BR = whatsnew/3.13.po -source_file = ../../pot/whatsnew/3.13.pot +[o:python-doc:p:python-313:r:whatsnew--3_13] +file_filter = whatsnew/3.13.po 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 -trans.pt_BR = whatsnew/3.2.po -source_file = ../../pot/whatsnew/3.2.pot +[o:python-doc:p:python-313:r:whatsnew--3_2] +file_filter = whatsnew/3.2.po 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 -trans.pt_BR = whatsnew/3.3.po -source_file = ../../pot/whatsnew/3.3.pot +[o:python-doc:p:python-313:r:whatsnew--3_3] +file_filter = whatsnew/3.3.po 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 -trans.pt_BR = whatsnew/3.4.po -source_file = ../../pot/whatsnew/3.4.pot +[o:python-doc:p:python-313:r:whatsnew--3_4] +file_filter = whatsnew/3.4.po 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 -trans.pt_BR = whatsnew/3.5.po -source_file = ../../pot/whatsnew/3.5.pot +[o:python-doc:p:python-313:r:whatsnew--3_5] +file_filter = whatsnew/3.5.po 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 -trans.pt_BR = whatsnew/3.6.po -source_file = ../../pot/whatsnew/3.6.pot +[o:python-doc:p:python-313:r:whatsnew--3_6] +file_filter = whatsnew/3.6.po 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 -trans.pt_BR = whatsnew/3.7.po -source_file = ../../pot/whatsnew/3.7.pot +[o:python-doc:p:python-313:r:whatsnew--3_7] +file_filter = whatsnew/3.7.po 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 -trans.pt_BR = whatsnew/3.8.po -source_file = ../../pot/whatsnew/3.8.pot +[o:python-doc:p:python-313:r:whatsnew--3_8] +file_filter = whatsnew/3.8.po 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 -trans.pt_BR = whatsnew/3.9.po -source_file = ../../pot/whatsnew/3.9.pot +[o:python-doc:p:python-313:r:whatsnew--3_9] +file_filter = whatsnew/3.9.po 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 -trans.pt_BR = whatsnew/changelog.po -source_file = ../../pot/whatsnew/changelog.pot +[o:python-doc:p:python-313:r:whatsnew--changelog] +file_filter = whatsnew/changelog.po 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 -trans.pt_BR = whatsnew/index.po -source_file = ../../pot/whatsnew/index.pot +[o:python-doc:p:python-313:r:whatsnew--index] +file_filter = whatsnew/index.po 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..5c038d29a 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 +# python-doc bot, 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-10-05 14:53+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,21 +77,21 @@ 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 " "Python source distribution for a partial list of contributors." msgstr "" -"Muitas pessoas tem contribuído para a linguagem Python, sua biblioteca " +"Muitas pessoas têm contribuído para a linguagem Python, sua biblioteca " "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..9b788b972 100644 --- a/bugs.po +++ b/bugs.po @@ -1,28 +1,27 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Adorilson Bezerra , 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-10-27 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Adorilson Bezerra , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,7 +37,7 @@ msgid "" msgstr "" "O Python é uma linguagem de programação madura que estabeleceu uma reputação " "pela estabilidade. A fim de manter esta reputação os desenvolvedores " -"gostariam de saber de quaisquer deficiências que você encontrar no Python." +"gostariam de saber de quaisquer deficiências que você encontre no Python." #: ../../bugs.rst:11 msgid "" @@ -46,9 +45,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" @@ -57,14 +56,26 @@ msgstr "Bugs na documentação" #: ../../bugs.rst:18 msgid "" "If you find a bug in this documentation or would like to propose an " -"improvement, please submit a bug report on the :ref:`tracker `. If you have a suggestion on how to fix it, include that as well." +"improvement, please submit a bug report on the :ref:`issue tracker `. If you have a suggestion on how to fix it, include that as " +"well." msgstr "" "Se você achar um bug nesta documentação ou gostaria de propor uma melhoria, " -"por favor submeta um relatório no :ref:`rastreador `. Se " -"você tem uma sugestão sobre como consertá-lo inclua isso também." +"por favor submeta um relatório no :ref:`rastreador de problemas `. Se você tiver uma sugestão sobre como consertá-lo inclua isso " +"também." + +#: ../../bugs.rst:24 +msgid "" +"If the bug or suggested improvement concerns the translation of this " +"documentation, submit the report to the `translation’s repository " +"`_ instead." +msgstr "" +"Se o bug ou a melhoria sugerida estiver relacionado à tradução desta " +"documentação, envie o relatório para o `repositório de tradução " +"`_." -#: ../../bugs.rst:22 +#: ../../bugs.rst:28 msgid "" "You can also open a discussion item on our `Documentation Discourse forum " "`_." @@ -72,34 +83,21 @@ msgstr "" "Você também pode abrir um item de discussão em nosso `fórum Discourse de " "documentação `_." -#: ../../bugs.rst:25 +#: ../../bugs.rst:31 msgid "" "If you find a bug in the theme (HTML / CSS / JavaScript) of the " -"documentation, please submit a bug report on the `python-doc-theme bug " +"documentation, please submit a bug report on the `python-doc-theme issue " "tracker `_." msgstr "" "Se você encontrar um bug no tema (HTML/CSS/JavaScript) da documentação, " -"envie um relatório de bug no `rastreador de bugs do python-doc-theme " +"envie um relatório de bug no `rastreador de problemas do python-doc-theme " "`_." -#: ../../bugs.rst:29 -msgid "" -"If you're short on time, you can also email documentation bug reports to " -"docs@python.org (behavioral bugs can be sent to python-list@python.org). " -"'docs@' is a mailing list run by volunteers; your request will be noticed, " -"though it may take a while to be processed." -msgstr "" -"Se você está com pouco tempo, pode também enviar os relatórios de erros de " -"documentação para o e-mail docs@python.org (erros de funcionalidades podem " -"ser enviados para python-list@python.org). 'docs@' é uma lista de discussão " -"mantida por voluntários; seu pedido será recebido, embora possa levar um " -"tempo para ser processado." - -#: ../../bugs.rst:36 +#: ../../bugs.rst:37 msgid "`Documentation bugs`_" msgstr "`Bugs na documentação`_" -#: ../../bugs.rst:37 +#: ../../bugs.rst:38 msgid "" "A list of documentation bugs that have been submitted to the Python issue " "tracker." @@ -107,25 +105,25 @@ msgstr "" "Uma lista de bugs na documentação que foram submetidos no rastreador de " "problemas do Python." -#: ../../bugs.rst:39 +#: ../../bugs.rst:40 msgid "`Issue Tracking `_" msgstr "`Rastreando problemas `_" -#: ../../bugs.rst:40 +#: ../../bugs.rst:41 msgid "" "Overview of the process involved in reporting an improvement on the tracker." msgstr "" "Visão geral do processo envolvido em reportar uma melhoria no rastreador." -#: ../../bugs.rst:42 +#: ../../bugs.rst:43 msgid "" "`Helping with Documentation `_" msgstr "" -"`Ajudando com a Documentação `_" -#: ../../bugs.rst:43 +#: ../../bugs.rst:44 msgid "" "Comprehensive guide for individuals that are interested in contributing to " "Python documentation." @@ -133,15 +131,15 @@ msgstr "" "Guia compreensivo para os indivíduos que estão interessados em contribuir " "com a documentação do Python." -#: ../../bugs.rst:45 +#: ../../bugs.rst:46 msgid "" "`Documentation Translations `_" msgstr "" -"`Traduções da Documentação `_" -#: ../../bugs.rst:46 +#: ../../bugs.rst:47 msgid "" "A list of GitHub pages for documentation translation and their primary " "contacts." @@ -149,11 +147,11 @@ msgstr "" "Uma lista de páginas no GitHub relacionadas à tradução da documentação e " "respectivos contatos iniciais." -#: ../../bugs.rst:52 +#: ../../bugs.rst:53 msgid "Using the Python issue tracker" msgstr "Usando o rastreador de problemas do Python" -#: ../../bugs.rst:54 +#: ../../bugs.rst:55 msgid "" "Issue reports for Python itself should be submitted via the GitHub issues " "tracker (https://github.com/python/cpython/issues). The GitHub issues " @@ -165,7 +163,7 @@ msgstr "" "rastreador de problemas do GitHub oferece um formulário web que permite " "informações pertinentes serem enviadas para os desenvolvedores." -#: ../../bugs.rst:59 +#: ../../bugs.rst:60 msgid "" "The first step in filing a report is to determine whether the problem has " "already been reported. The advantage in doing so, aside from saving the " @@ -183,7 +181,7 @@ msgstr "" "fornecê-la se você puder!). Para fazer isso, procure no rastreador usando a " "caixa de busca no topo da página." -#: ../../bugs.rst:66 +#: ../../bugs.rst:67 msgid "" "If the problem you're reporting is not already in the list, log in to " "GitHub. If you don't already have a GitHub account, create a new account " @@ -195,7 +193,7 @@ msgstr "" "usando o link \"Sign Up\". Não é possível enviar um relatório de bug " "anonimamente." -#: ../../bugs.rst:71 +#: ../../bugs.rst:72 msgid "" "Being now logged in, you can submit an issue. Click on the \"New issue\" " "button in the top bar to report a new issue." @@ -204,11 +202,11 @@ msgstr "" "Clique no botão \"New issue\" na barra superior para relatar um novo " "problema." -#: ../../bugs.rst:74 +#: ../../bugs.rst:75 msgid "The submission form has two fields, \"Title\" and \"Comment\"." msgstr "O formulário de submissão tem dois campos, \"Title\" e \"Comment\"." -#: ../../bugs.rst:76 +#: ../../bugs.rst:77 msgid "" "For the \"Title\" field, enter a *very* short description of the problem; " "fewer than ten words is good." @@ -216,7 +214,7 @@ msgstr "" "Para o campo \"Title\", insira uma descrição *muito* curta do problema; " "menos de dez palavras é bom." -#: ../../bugs.rst:79 +#: ../../bugs.rst:80 msgid "" "In the \"Comment\" field, describe the problem in detail, including what you " "expected to happen and what did happen. Be sure to include whether any " @@ -229,7 +227,7 @@ msgstr "" "plataforma de software você está usando (incluindo informações sobre a " "versão quando apropriado)." -#: ../../bugs.rst:84 +#: ../../bugs.rst:85 msgid "" "Each issue report will be reviewed by a developer who will determine what " "needs to be done to correct the problem. You will receive an update each " @@ -239,15 +237,15 @@ msgstr "" "determinar o que é necessário para solucionar o problema. Você receberá " "atualizações para cada ação tomada para o problema." -#: ../../bugs.rst:91 +#: ../../bugs.rst:92 msgid "" "`How to Report Bugs Effectively `_" msgstr "" -"`Como Reportar Bugs Eficientemente `_" -#: ../../bugs.rst:92 +#: ../../bugs.rst:93 msgid "" "Article which goes into some detail about how to create a useful bug report. " "This describes what kind of information is useful and why it is useful." @@ -255,7 +253,7 @@ msgstr "" "Artigo que entra em algum detalhe sobre como criar um relatório de bug útil. " "Isto descreve qual tipo de informação é útil e por quê é útil." -#: ../../bugs.rst:95 +#: ../../bugs.rst:96 msgid "" "`Bug Writing Guidelines `_" @@ -263,7 +261,7 @@ msgstr "" "`Diretrizes para relatar bugs `_" -#: ../../bugs.rst:96 +#: ../../bugs.rst:97 msgid "" "Information about writing a good bug report. Some of this is specific to " "the Mozilla project, but describes general good practices." @@ -271,11 +269,11 @@ msgstr "" "Informação sobre como escrever um bom relatório de bug. Um pouco disto é " "específico do Projeto Mozilla, mas descreve boas práticas em geral." -#: ../../bugs.rst:102 +#: ../../bugs.rst:103 msgid "Getting started contributing to Python yourself" msgstr "Começando a contribuir com o Python por conta própria" -#: ../../bugs.rst:104 +#: ../../bugs.rst:105 msgid "" "Beyond just reporting bugs that you find, you are also welcome to submit " "patches to fix them. You can find more information on how to get started " diff --git a/c-api/abstract.po b/c-api/abstract.po index 3a5bad996..13beac8eb 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..87ff92317 100644 --- a/c-api/allocation.po +++ b/c-api/allocation.po @@ -1,48 +1,44 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# Gustavo Reis, 2025 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/allocation.rst:6 msgid "Allocating Objects on the Heap" -msgstr "Alocando Objetos na Pilha" +msgstr "Alocando objetos na heap" #: ../../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 +46,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 +62,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,21 +94,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 "" -"Releases memory allocated to an object using :c:macro:`PyObject_New` or :c:" -"macro:`PyObject_NewVar`. This is normally called from the :c:member:" -"`~PyTypeObject.tp_dealloc` handler specified in the object's type. The " -"fields of the object should not be accessed after this call as the memory is " -"no longer a valid Python object." +"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 "" -"Libera memória alocada a um objeto usando :c:macro:`PyObject_New` ou :c:" -"macro:`PyObject_NewVar`. Isto é normalmente chamado pelo manipulador de :c:" -"member:`~PyTypeObject.tp_dealloc` especificado no tipo do objeto. Os campos " -"do objeto não devem ser acessados após esta chamada como a memória não é " -"mais um objeto Python válido." +"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:66 +#: ../../c-api/allocation.rst:63 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 +114,60 @@ msgstr "" "usando a macro :c:macro:`Py_None`, o qual avalia como um ponteiro para este " "objeto." -#: ../../c-api/allocation.rst:73 -msgid ":c:func:`PyModule_Create`" -msgstr ":c:func:`PyModule_Create`" +#: ../../c-api/allocation.rst:70 +msgid ":ref:`moduleobjects`" +msgstr ":ref:`moduleobjects`" -#: ../../c-api/allocation.rst:74 +#: ../../c-api/allocation.rst:71 msgid "To allocate and create extension modules." msgstr "Para alocar e criar módulos de extensão." + +#: ../../c-api/allocation.rst:75 +msgid "Deprecated aliases" +msgstr "Apelidos descontinuados" + +#: ../../c-api/allocation.rst:77 +msgid "" +"These are :term:`soft deprecated` aliases to existing functions and macros. " +"They exist solely for backwards compatibility." +msgstr "" +"Esses são apelidos :term:`suavemente descontinuados ` para funções e macros existentes. Eles existem unicamente " +"para fins de retrocompatibilidade." + +#: ../../c-api/allocation.rst:85 +msgid "Deprecated alias" +msgstr "Apelido descontinuado" + +#: ../../c-api/allocation.rst:86 +msgid "Function" +msgstr "Função" + +#: ../../c-api/allocation.rst:88 +msgid ":c:macro:`PyObject_New`" +msgstr ":c:macro:`PyObject_New`" + +#: ../../c-api/allocation.rst:90 +msgid ":c:macro:`PyObject_NewVar`" +msgstr ":c:macro:`PyObject_NewVar`" + +#: ../../c-api/allocation.rst:92 +msgid ":c:func:`PyObject_Init`" +msgstr ":c:func:`PyObject_Init`" + +#: ../../c-api/allocation.rst:94 +msgid ":c:func:`PyObject_InitVar`" +msgstr ":c:func:`PyObject_InitVar`" + +#: ../../c-api/allocation.rst:96 +msgid ":c:func:`PyObject_Malloc`" +msgstr ":c:func:`PyObject_Malloc`" + +#: ../../c-api/allocation.rst:98 +msgid ":c:func:`PyObject_Realloc`" +msgstr ":c:func:`PyObject_Realloc`" + +#: ../../c-api/allocation.rst:100 ../../c-api/allocation.rst:102 +#: ../../c-api/allocation.rst:104 +msgid ":c:func:`PyObject_Free`" +msgstr ":c:func:`PyObject_Free`" diff --git a/c-api/apiabiversion.po b/c-api/apiabiversion.po index 49af33910..7babcba18 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0d86959e0 100644 --- a/c-api/arg.po +++ b/c-api/arg.po @@ -1,35 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-27 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +30,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 +146,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,10 +203,10 @@ 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:" -"`PyUnicode_FSConverter` como *conversor*." +"Esse formato não aceita :term:`objetos bytes ou similares `. Se você quer aceitar caminhos de sistema de arquivos e convertê-" +"los para strings de caracteres em C, é preferível que use o formato ``O&`` " +"com :c:func:`PyUnicode_FSConverter` como *conversor*." #: ../../c-api/arg.rst:96 msgid "" @@ -227,9 +218,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 +227,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 similares. " "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 +237,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 +254,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 \\*]" @@ -274,45 +263,44 @@ msgid "" "Like ``s``, but the Python object may also be ``None``, in which case the C " "pointer is set to ``NULL``." msgstr "" -"Como ``s``, mas o objeto Python também pode ser ``None``, nesse caso o " +"Como ``s``, mas o objeto Python também pode ser ``None``, caso em que o " "ponteiro C é definido como ``NULL``." #: ../../c-api/arg.rst:117 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 "" "Like ``s*``, but the Python object may also be ``None``, in which case the " "``buf`` member of the :c:type:`Py_buffer` structure is set to ``NULL``." msgstr "" -"Como ``s*``, mas o objeto Python também pode ser ``None``, nesse caso o " -"membro ``buf`` da estrutura :c:type:`Py_buffer` é definido como ``NULL``." +"Como ``s*``, mas o objeto Python também pode ser ``None``, caso em que o " +"membro ``buf`` da estrutura :c:type:`Py_buffer` é definida como ``NULL``." #: ../../c-api/arg.rst:121 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 "" "Like ``s#``, but the Python object may also be ``None``, in which case the C " "pointer is set to ``NULL``." msgstr "" -"Como ``s#``, mas o objeto Python também pode ser ``None``, nesse caso o " +"Como ``s#``, mas o objeto Python também pode ser ``None``, caso em que o " "ponteiro C é definido como ``NULL``." #: ../../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 +309,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,32 +324,31 @@ 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 " -"similar. **Esta é a maneira recomendada para aceitar dados binários.**" +"Esta variante em ``s*`` não aceita objetos unicode, apenas objetos bytes ou " +"similares. **Esta é a maneira recomendada para aceitar dados binários.**" #: ../../c-api/arg.rst:141 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 " -"similar." +"Esta variação de ``s#`` não aceita objetos Unicode, apenas objetos bytes ou " +"similares." #: ../../c-api/arg.rst:145 msgid "``S`` (:class:`bytes`) [PyBytesObject \\*]" @@ -410,14 +397,13 @@ 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 "" "This format accepts any object which implements the read-write buffer " "interface. It fills a :c:type:`Py_buffer` structure provided by the caller. " -"The buffer may contain embedded null bytes. The caller have to call :c:func:" +"The buffer may contain embedded null bytes. The caller has to call :c:func:" "`PyBuffer_Release` when it is done with the buffer." msgstr "" "Este formato aceita qualquer objeto que implemente a interface do buffer de " @@ -483,7 +469,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 +569,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 +586,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 +656,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 +676,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 +696,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 +716,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 +736,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 +752,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 +799,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 +817,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 +833,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 +852,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 +896,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 +911,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 +919,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 +937,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 +954,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 +968,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 +982,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 +992,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 +1008,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 +1025,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 +1039,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 +1047,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 +1064,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 +1074,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 +1082,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 +1092,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 +1100,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 +1110,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 +1120,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 +1181,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 +1189,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 +1225,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 +1243,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 +1259,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 +1275,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 +1294,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 +1306,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 +1317,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 +1330,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 +1346,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 +1358,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 +1370,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 +1398,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 +1412,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 +1489,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 +1497,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 +1534,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 +1556,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 +1572,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 +1580,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 +1592,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 +1606,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 +1614,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..c7375ca9b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..2e6969692 100644 --- a/c-api/buffer.po +++ b/c-api/buffer.po @@ -1,44 +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 -# (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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/buffer.rst:11 msgid "Buffer Protocol" -msgstr "Protocolo de Buffer" +msgstr "Protocolo de buffer" #: ../../c-api/buffer.rst:18 msgid "" @@ -49,10 +37,10 @@ msgid "" "image processing or numeric analysis." msgstr "" "Certos objetos disponíveis no Python envolvem o acesso a um vetor ou " -"*buffer* de memória subjacente. Esses objetos incluem as :class:`bytes` e :" -"class:`bytearray` embutidas, e alguns tipos de extensão como :class:`array." -"array`. As bibliotecas de terceiros podem definir seus próprios tipos para " -"fins especiais, como processamento de imagem ou análise numérica." +"*buffer* de memória subjacente. Esses objetos incluem as classes :class:" +"`bytes` e :class:`bytearray` embutidas, e alguns tipos de extensão como :" +"class:`array.array`. As bibliotecas de terceiros podem definir seus próprios " +"tipos para fins especiais, como processamento de imagem ou análise numérica." #: ../../c-api/buffer.rst:24 msgid "" @@ -68,31 +56,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 +96,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 " @@ -118,14 +110,14 @@ msgstr "" "Um exemplo de interface de um consumidor de buffer é o método :meth:`~io." "BufferedIOBase.write` de objetos arquivo: qualquer objeto que possa exportar " "uma série de bytes por meio da interface de buffer pode ser gravado em um " -"arquivo. Enquanto o :meth:`!write` precisa apenas de acesso de somente " +"arquivo. Enquanto o :meth:`!write` precisa apenas de acesso somente de " "leitura ao conteúdo interno do objeto passado, outros métodos, como :meth:" -"`~io.BufferedIOBase.readinto`, precisam de acesso de somente escrita ao " -"conteúdo interno. A interface de buffer permite que o objetos possam " +"`~io.BufferedIOBase.readinto`, precisam de acesso somente de escrita ao " +"conteúdo interno. A interface de buffer permite que os objetos possam " "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,33 +125,41 @@ 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;" +msgstr "chamar :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 `." 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*``." +"chamar :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 " "resource leaks." msgstr "" "Em ambos os casos, :c:func:`PyBuffer_Release` deve ser chamado quando o " -"buffer não é mais necessário. A falta de tal pode levar a várias questões, " +"buffer não é mais necessário. A falta de tal pode levar a vários problemas, " "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 +180,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 +194,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 +204,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 +216,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 +224,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 " @@ -234,10 +234,10 @@ msgstr "" "Uma nova referência ao objeto sendo exporta. A referência pertence ao " "consumidor e é automaticamente liberada (por exemplo, a contagem de " "referências é decrementada) e é atribuída para ``NULL`` por :c:func:" -"`PyBuffer_Release`. O campo é equivalmente ao valor de retorno de qualquer " -"função do padrão C-API." +"`PyBuffer_Release`. O campo equivale ao valor de retorno de qualquer função " +"padrão da API C." -#: ../../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 +247,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 +259,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 +271,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 +279,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 +288,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 +300,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 +310,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 +320,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 +330,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 +348,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 +360,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 +368,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 +381,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 +392,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 +411,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 +419,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 +429,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,26 +446,26 @@ 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 " "handle up to :c:macro:`!PyBUF_MAX_NDIM` dimensions. Currently set to 64." msgstr "" "O número máximo de dimensões que a memória representa. Exportadores DEVEM " -"respeitar esse limite, consumidores de buffers multi-dimensionais DEVEM ser " -"capazes de liader com até :c:macro:`!PyBUF_MAX_NDIM` dimensões. Atualmente " +"respeitar esse limite, consumidores de buffers multidimensionais DEVEM ser " +"capazes de lidar 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 +478,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 +501,32 @@ 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 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:266 +msgid "This is a :term:`soft deprecated` alias to :c:macro:`PyBUF_WRITABLE`." 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." +"Este é um apelido :term:`suavemente descontinuado` para :c:macro:" +"`PyBUF_WRITABLE`." -#: ../../c-api/buffer.rst:260 +#: ../../c-api/buffer.rst:270 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 +535,7 @@ msgstr "" "DEVE ser preenchido corretamente. Caso contrário, este campo DEVE ser " "``NULL``." -#: ../../c-api/buffer.rst:264 +#: ../../c-api/buffer.rst:274 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 +547,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:278 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:284 msgid "shape, strides, suboffsets" msgstr "forma, avanços, suboffsets" -#: ../../c-api/buffer.rst:275 +#: ../../c-api/buffer.rst:286 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 +572,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:293 ../../c-api/buffer.rst:317 +#: ../../c-api/buffer.rst:342 msgid "Request" msgstr "Solicitação" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:293 ../../c-api/buffer.rst:317 +#: ../../c-api/buffer.rst:342 msgid "shape" msgstr "Forma" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:293 ../../c-api/buffer.rst:317 +#: ../../c-api/buffer.rst:342 msgid "strides" msgstr "Avanços" -#: ../../c-api/buffer.rst:282 ../../c-api/buffer.rst:306 -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:293 ../../c-api/buffer.rst:317 +#: ../../c-api/buffer.rst:342 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:295 ../../c-api/buffer.rst:297 +#: ../../c-api/buffer.rst:299 ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:321 ../../c-api/buffer.rst:323 +#: ../../c-api/buffer.rst:325 ../../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 ../../c-api/buffer.rst:356 +#: ../../c-api/buffer.rst:358 msgid "yes" msgstr "sim" -#: ../../c-api/buffer.rst:284 ../../c-api/buffer.rst:333 -#: ../../c-api/buffer.rst:335 +#: ../../c-api/buffer.rst:295 ../../c-api/buffer.rst:344 +#: ../../c-api/buffer.rst:346 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:297 ../../c-api/buffer.rst:299 +#: ../../c-api/buffer.rst:301 ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:321 ../../c-api/buffer.rst:323 +#: ../../c-api/buffer.rst:325 ../../c-api/buffer.rst:348 +#: ../../c-api/buffer.rst:350 ../../c-api/buffer.rst:352 +#: ../../c-api/buffer.rst:354 ../../c-api/buffer.rst:356 +#: ../../c-api/buffer.rst:358 msgid "NULL" msgstr "NULL" -#: ../../c-api/buffer.rst:297 +#: ../../c-api/buffer.rst:308 msgid "contiguity requests" msgstr "requisições contíguas" -#: ../../c-api/buffer.rst:299 +#: ../../c-api/buffer.rst:310 msgid "" "C or Fortran :term:`contiguity ` can be explicitly requested, " "with and without stride information. Without stride information, the buffer " @@ -621,32 +632,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:317 ../../c-api/buffer.rst:342 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:319 ../../c-api/buffer.rst:325 +#: ../../c-api/buffer.rst:356 ../../c-api/buffer.rst:358 msgid "C" msgstr "C" -#: ../../c-api/buffer.rst:310 +#: ../../c-api/buffer.rst:321 msgid "F" msgstr "F" -#: ../../c-api/buffer.rst:312 +#: ../../c-api/buffer.rst:323 msgid "C or F" msgstr "C ou F" -#: ../../c-api/buffer.rst:314 +#: ../../c-api/buffer.rst:325 msgid ":c:macro:`PyBUF_ND`" msgstr ":c:macro:`PyBUF_ND`" -#: ../../c-api/buffer.rst:319 +#: ../../c-api/buffer.rst:330 msgid "compound requests" msgstr "requisições compostas" -#: ../../c-api/buffer.rst:321 +#: ../../c-api/buffer.rst:332 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 +668,7 @@ msgstr "" "protocolo do buffer fornece combinações frequentemente utilizadas como " "sinalizadores únicos." -#: ../../c-api/buffer.rst:325 +#: ../../c-api/buffer.rst:336 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 +676,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:342 msgid "readonly" msgstr "readonly" -#: ../../c-api/buffer.rst:331 +#: ../../c-api/buffer.rst:342 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: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 "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:344 ../../c-api/buffer.rst:348 +#: ../../c-api/buffer.rst:352 ../../c-api/buffer.rst:356 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:346 ../../c-api/buffer.rst:350 +#: ../../c-api/buffer.rst:354 ../../c-api/buffer.rst:358 msgid "1 or 0" msgstr "1 ou 0" -#: ../../c-api/buffer.rst:352 +#: ../../c-api/buffer.rst:363 msgid "Complex arrays" msgstr "Vetores Complexos" -#: ../../c-api/buffer.rst:355 +#: ../../c-api/buffer.rst:366 msgid "NumPy-style: shape and strides" msgstr "Estilo NumPy: forma e avanços" -#: ../../c-api/buffer.rst:357 +#: ../../c-api/buffer.rst:368 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 +718,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:371 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 +730,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:375 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 +740,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:379 +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:385 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 +760,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:389 +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:419 msgid "PIL-style: shape, strides and suboffsets" msgstr "Estilo-PIL: forma, avanços e suboffsets" -#: ../../c-api/buffer.rst:410 +#: ../../c-api/buffer.rst:421 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 +837,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:430 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 +847,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:434 +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:449 msgid "Buffer-related functions" msgstr "Funções relacionadas ao Buffer" -#: ../../c-api/buffer.rst:442 +#: ../../c-api/buffer.rst:453 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 +889,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:460 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 +900,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:465 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 +913,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:470 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 +925,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:478 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 +937,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:483 msgid "" "It is an error to call this function on a buffer that was not obtained via :" "c:func:`PyObject_GetBuffer`." @@ -842,7 +945,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:489 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 +953,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:497 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 +965,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:504 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 +973,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:510 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 +983,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:517 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 +994,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:521 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:526 msgid "" "Copy data from *src* to *dest* buffer. Can convert between C-style and or " "Fortran-style buffers." @@ -903,11 +1006,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:529 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:533 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 +1020,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:540 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 +1030,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:544 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 +1040,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:548 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 +1050,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:552 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 +1081,14 @@ msgstr "objeto buffer" msgid "PyBufferProcs (C type)" msgstr "PyBufferProcs (tipo C)" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:305 msgid "contiguous" msgstr "contíguo" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:305 msgid "C-contiguous" msgstr "contíguo C" -#: ../../c-api/buffer.rst:294 +#: ../../c-api/buffer.rst:305 msgid "Fortran contiguous" msgstr "contíguo Fortran" diff --git a/c-api/bytearray.po b/c-api/bytearray.po index cc26922a9..d10b8066c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..d985dfa4f 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 +# python-doc bot, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -409,6 +402,57 @@ msgstr "" "originais em *\\*bytes* é desalocado, *\\*bytes* é definido como ``NULL``, :" "exc:`MemoryError` é definido e ``-1`` é retornado." +#: ../../c-api/bytes.rst:208 +msgid "" +"Get the string representation of *bytes*. This function is currently used to " +"implement :meth:`!bytes.__repr__` in Python." +msgstr "" + +#: ../../c-api/bytes.rst:211 +msgid "" +"This function does not do type checking; it is undefined behavior to pass " +"*bytes* as a non-bytes object or ``NULL``." +msgstr "" + +#: ../../c-api/bytes.rst:214 +msgid "" +"If *smartquotes* is true, the representation will use a double-quoted string " +"instead of single-quoted string when single-quotes are present in *bytes*. " +"For example, the byte string ``'Python'`` would be represented as " +"``b\"'Python'\"`` when *smartquotes* is true, or ``b'\\'Python\\''`` when it " +"is false." +msgstr "" + +#: ../../c-api/bytes.rst:220 +msgid "" +"On success, this function returns a :term:`strong reference` to a :class:" +"`str` object containing the representation. On failure, this returns " +"``NULL`` with an exception set." +msgstr "" + +#: ../../c-api/bytes.rst:227 +msgid "" +"Unescape a backslash-escaped string *s*. *s* must not be ``NULL``. *len* " +"must be the size of *s*." +msgstr "" + +#: ../../c-api/bytes.rst:230 +msgid "" +"*errors* must be one of ``\"strict\"``, ``\"replace\"``, or ``\"ignore\"``. " +"If *errors* is ``NULL``, then ``\"strict\"`` is used by default." +msgstr "" + +#: ../../c-api/bytes.rst:233 +msgid "" +"On success, this function returns a :term:`strong reference` to a Python :" +"class:`bytes` object containing the unescaped string. On failure, this " +"function returns ``NULL`` with an exception set." +msgstr "" + +#: ../../c-api/bytes.rst:237 +msgid "*unicode* and *recode_encoding* are now unused." +msgstr "" + #: ../../c-api/bytes.rst:11 msgid "object" msgstr "objeto" diff --git a/c-api/call.po b/c-api/call.po index e9470409d..4d41183a3 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 " @@ -78,8 +77,8 @@ msgid "" "To call an object, use :c:func:`PyObject_Call` or another :ref:`call API " "`." msgstr "" -"Para chamar um objeto, use :c:func:`PyObject_Call` ou outra :ref:`call API " -"`." +"Para chamar um objeto, use :c:func:`PyObject_Call` ou outra :ref:`API de " +"chamada `." #: ../../c-api/call.rst:36 msgid "The Vectorcall Protocol" @@ -104,10 +103,10 @@ msgid "" "achieve this is by setting :c:member:`~PyTypeObject.tp_call` to :c:func:" "`PyVectorcall_Call`. This bears repeating:" msgstr "" -"Como regra de bolso. CPython vai preferir o vectorcall para invocações " -"internas se o chamável suportar. Entretanto, isso não é uma regra rígida. " -"Ademais, alguma extensões de terceiros usam diretamente *tp_call* (em vez " -"de utilizar :c:func:`PyObject_Call`). Portanto, uma classe que suporta " +"Como regra de ouro, CPython vai preferir o vectorcall para chamadas internas " +"se o chamável suportar. Entretanto, isso não é uma regra rígida. Ademais, " +"alguma extensões de terceiros usam *tp_call* diretamente (em vez de " +"utilizar :c:func:`PyObject_Call`). Portanto, uma classe que suporta " "vectorcall precisa também implementar :c:member:`~PyTypeObject.tp_call`. " "Além disso, o chamável precisa se comportar da mesma forma independe de qual " "protocolo é utilizado. A forma recomendada de alcançar isso é definindo :c:" @@ -131,12 +130,12 @@ msgid "" "versions, vectorcall should only be used with :c:macro:`immutable " "` or static types." msgstr "" -"O sinalizador :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` agora é removida da " +"O sinalizador :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` agora é removido da " "classe quando o método :py:meth:`~object.__call__` está reatribuído. " "(Internamente, isso apenas define :c:member:`~PyTypeObject.tp_call`, e " -"portanto, pode fazê-lo comportar-se de forma diferente da função vetorcall. " +"portanto, pode fazê-lo comportar-se de forma diferente da função vectorcall. " "Em versões anteriores do Python, vectorcall só deve ser usado com tipos :c:" -"macro:`imutáveis ` ou estáticos." +"macro:`imutáveis ` ou estáticos." #: ../../c-api/call.rst:69 msgid "" @@ -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..de963a9f5 100644 --- a/c-api/capsule.po +++ b/c-api/capsule.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,7 +38,7 @@ msgstr "" #: ../../c-api/capsule.rst:17 msgid "" "This subtype of :c:type:`PyObject` represents an opaque value, useful for C " -"extension modules who need to pass an opaque value (as a :c:expr:`void*` " +"extension modules which need to pass an opaque value (as a :c:expr:`void*` " "pointer) through Python code to other C code. It is often used to make a C " "function pointer defined in one module available to other modules, so the " "regular import mechanism can be used to access C APIs defined in dynamically " @@ -52,11 +53,23 @@ msgstr "" "dinamicamente." #: ../../c-api/capsule.rst:27 +msgid "" +"The type object corresponding to capsule objects. This is the same object " +"as :class:`types.CapsuleType` in the Python layer." +msgstr "" +"O objeto de tipo correspondente aos objetos cápsula. Este é o mesmo objeto " +"que :class:`types.CapsuleType` na camada Python." + +#: ../../c-api/capsule.rst:33 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:31 +#: ../../c-api/capsule.rst:35 +msgid "typedef void (*PyCapsule_Destructor)(PyObject *);" +msgstr "typedef void (*PyCapsule_Destructor)(PyObject *);" + +#: ../../c-api/capsule.rst:37 msgid "" "See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor " "callbacks." @@ -64,7 +77,7 @@ msgstr "" "Veja :c:func:`PyCapsule_New` para a semântica dos retornos de chamada " "PyCapsule_Destructor." -#: ../../c-api/capsule.rst:37 +#: ../../c-api/capsule.rst:43 msgid "" "Return true if its argument is a :c:type:`PyCapsule`. This function always " "succeeds." @@ -72,7 +85,7 @@ msgstr "" "Retorna true se seu argumento é um :c:type:`PyCapsule`. Esta função sempre " "tem sucesso." -#: ../../c-api/capsule.rst:43 +#: ../../c-api/capsule.rst:49 msgid "" "Create a :c:type:`PyCapsule` encapsulating the *pointer*. The *pointer* " "argument may not be ``NULL``." @@ -80,11 +93,11 @@ msgstr "" "Cria um :c:type:`PyCapsule` que encapsula o *ponteiro*. O argumento " "*pointer* pode não ser ``NULL``." -#: ../../c-api/capsule.rst:46 +#: ../../c-api/capsule.rst:52 msgid "On failure, set an exception and return ``NULL``." msgstr "Em caso de falha, define uma exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:48 +#: ../../c-api/capsule.rst:54 msgid "" "The *name* string may either be ``NULL`` or a pointer to a valid C string. " "If non-``NULL``, this string must outlive the capsule. (Though it is " @@ -94,7 +107,7 @@ msgstr "" "Se não for ``NULL``, essa string deverá sobreviver à cápsula. (Embora seja " "permitido liberá-lo dentro do *descructor*.)" -#: ../../c-api/capsule.rst:52 +#: ../../c-api/capsule.rst:58 msgid "" "If the *destructor* argument is not ``NULL``, it will be called with the " "capsule as its argument when it is destroyed." @@ -102,7 +115,7 @@ msgstr "" "Se o argumento *destructor* não for ``NULL``, ele será chamado com a cápsula " "como argumento quando for destruído." -#: ../../c-api/capsule.rst:55 +#: ../../c-api/capsule.rst:61 msgid "" "If this capsule will be stored as an attribute of a module, the *name* " "should be specified as ``modulename.attributename``. This will enable other " @@ -112,7 +125,7 @@ msgstr "" "ser especificado como ``modulename.attributename``. Isso permitirá que " "outros módulos importem a cápsula usando :c:func:`PyCapsule_Import`." -#: ../../c-api/capsule.rst:62 +#: ../../c-api/capsule.rst:68 msgid "" "Retrieve the *pointer* stored in the capsule. On failure, set an exception " "and return ``NULL``." @@ -120,7 +133,7 @@ msgstr "" "Recupera o *pointer* armazenado na cápsula. Em caso de falha, define uma " "exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:65 +#: ../../c-api/capsule.rst:71 msgid "" "The *name* parameter must compare exactly to the name stored in the capsule. " "If the name stored in the capsule is ``NULL``, the *name* passed in must " @@ -132,7 +145,7 @@ msgstr "" "também deve ser ``NULL``. Python usa a função C :c:func:`!strcmp` para " "comparar nomes de cápsulas." -#: ../../c-api/capsule.rst:73 +#: ../../c-api/capsule.rst:79 msgid "" "Return the current destructor stored in the capsule. On failure, set an " "exception and return ``NULL``." @@ -140,7 +153,7 @@ msgstr "" "Retorna o destruidor atual armazenado na cápsula. Em caso de falha, define " "uma exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:76 +#: ../../c-api/capsule.rst:82 msgid "" "It is legal for a capsule to have a ``NULL`` destructor. This makes a " "``NULL`` return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :" @@ -150,7 +163,7 @@ msgstr "" "retorno ``NULL`` um tanto ambíguo; use :c:func:`PyCapsule_IsValid` ou :c:" "func:`PyErr_Occurred` para desambiguar." -#: ../../c-api/capsule.rst:83 +#: ../../c-api/capsule.rst:89 msgid "" "Return the current context stored in the capsule. On failure, set an " "exception and return ``NULL``." @@ -158,7 +171,7 @@ msgstr "" "Retorna o contexto atual armazenado na cápsula. Em caso de falha, define uma " "exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:86 +#: ../../c-api/capsule.rst:92 msgid "" "It is legal for a capsule to have a ``NULL`` context. This makes a ``NULL`` " "return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :c:func:" @@ -168,7 +181,7 @@ msgstr "" "retorno ``NULL`` um tanto ambíguo; use :c:func:`PyCapsule_IsValid` ou :c:" "func:`PyErr_Occurred` para desambiguar." -#: ../../c-api/capsule.rst:93 +#: ../../c-api/capsule.rst:99 msgid "" "Return the current name stored in the capsule. On failure, set an exception " "and return ``NULL``." @@ -176,7 +189,7 @@ msgstr "" "Retorna o nome atual armazenado na cápsula. Em caso de falha, define uma " "exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:96 +#: ../../c-api/capsule.rst:102 msgid "" "It is legal for a capsule to have a ``NULL`` name. This makes a ``NULL`` " "return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :c:func:" @@ -186,7 +199,7 @@ msgstr "" "retorno ``NULL`` um tanto ambíguo; use :c:func:`PyCapsule_IsValid` ou :c:" "func:`PyErr_Occurred` para desambiguar." -#: ../../c-api/capsule.rst:103 +#: ../../c-api/capsule.rst:109 msgid "" "Import a pointer to a C object from a capsule attribute in a module. The " "*name* parameter should specify the full name to the attribute, as in " @@ -198,7 +211,15 @@ msgstr "" "``module.attribute``. O *name* armazenado na cápsula deve corresponder " "exatamente a essa string." -#: ../../c-api/capsule.rst:108 +#: ../../c-api/capsule.rst:114 +msgid "" +"This function splits *name* on the ``.`` character, and imports the first " +"element. It then processes further elements using attribute lookups." +msgstr "" +"Esta função divide *name* no caractere ``.`` e importa o primeiro elemento. " +"Em seguida, processa os elementos seguintes usando pesquisas de atributos." + +#: ../../c-api/capsule.rst:117 msgid "" "Return the capsule's internal *pointer* on success. On failure, set an " "exception and return ``NULL``." @@ -206,11 +227,23 @@ msgstr "" "Retorna o ponteiro interno *pointer* da cápsula com sucesso. Em caso de " "falha, define uma exceção e retorna ``NULL``." -#: ../../c-api/capsule.rst:111 +#: ../../c-api/capsule.rst:122 +msgid "" +"If *name* points to an attribute of some submodule or subpackage, this " +"submodule or subpackage must be previously imported using other means (for " +"example, by using :c:func:`PyImport_ImportModule`) for the attribute lookups " +"to succeed." +msgstr "" +"Se *name* apontar para um atributo de algum submódulo ou subpacote, esse " +"submódulo ou subpacote deverá ser importado previamente usando outros meios " +"(por exemplo, usando :c:func:`PyImport_ImportModule`) para que as pesquisas " +"de atributos sejam bem-sucedidas." + +#: ../../c-api/capsule.rst:127 msgid "*no_block* has no effect anymore." msgstr "*no_block* não tem mais efeito." -#: ../../c-api/capsule.rst:117 +#: ../../c-api/capsule.rst:133 msgid "" "Determines whether or not *capsule* is a valid capsule. A valid capsule is " "non-``NULL``, passes :c:func:`PyCapsule_CheckExact`, has a non-``NULL`` " @@ -224,7 +257,7 @@ msgstr "" "parâmetro *name*. (Consulte :c:func:`PyCapsule_GetPointer` para obter " "informações sobre como os nomes das cápsulas são comparados.)" -#: ../../c-api/capsule.rst:123 +#: ../../c-api/capsule.rst:139 msgid "" "In other words, if :c:func:`PyCapsule_IsValid` returns a true value, calls " "to any of the accessors (any function starting with ``PyCapsule_Get``) are " @@ -234,7 +267,7 @@ msgstr "" "verdadeiro, as chamadas para qualquer um dos acessadores (qualquer função " "que comece com ``PyCapsule_Get``) terão êxito garantido." -#: ../../c-api/capsule.rst:127 +#: ../../c-api/capsule.rst:143 msgid "" "Return a nonzero value if the object is valid and matches the name passed " "in. Return ``0`` otherwise. This function will not fail." @@ -242,23 +275,23 @@ msgstr "" "Retorna um valor diferente de zero se o objeto for válido e corresponder ao " "nome passado. Retorna ``0`` caso contrário. Esta função não falhará." -#: ../../c-api/capsule.rst:133 +#: ../../c-api/capsule.rst:149 msgid "Set the context pointer inside *capsule* to *context*." msgstr "Define o ponteiro de contexto dentro de *capsule* para *context*." -#: ../../c-api/capsule.rst:135 ../../c-api/capsule.rst:142 -#: ../../c-api/capsule.rst:151 ../../c-api/capsule.rst:159 +#: ../../c-api/capsule.rst:151 ../../c-api/capsule.rst:158 +#: ../../c-api/capsule.rst:167 ../../c-api/capsule.rst:175 msgid "" "Return ``0`` on success. Return nonzero and set an exception on failure." msgstr "" "Retorna ``0`` em caso de sucesso. Retorna diferente de zero e define uma " "exceção em caso de falha." -#: ../../c-api/capsule.rst:140 +#: ../../c-api/capsule.rst:156 msgid "Set the destructor inside *capsule* to *destructor*." msgstr "Define o destrutor dentro de *capsule* para *destructor*." -#: ../../c-api/capsule.rst:147 +#: ../../c-api/capsule.rst:163 msgid "" "Set the name inside *capsule* to *name*. If non-``NULL``, the name must " "outlive the capsule. If the previous *name* stored in the capsule was not " @@ -268,7 +301,7 @@ msgstr "" "deve sobreviver à cápsula. Se o *name* anterior armazenado na cápsula não " "era ``NULL``, nenhuma tentativa será feita para liberá-lo." -#: ../../c-api/capsule.rst:156 +#: ../../c-api/capsule.rst:172 msgid "" "Set the void pointer inside *capsule* to *pointer*. The pointer may not be " "``NULL``." diff --git a/c-api/cell.po b/c-api/cell.po index 736a871da..cf31c80e9 100644 --- a/c-api/cell.po +++ b/c-api/cell.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,17 +32,17 @@ msgstr "Objeto célula" msgid "" "\"Cell\" objects are used to implement variables referenced by multiple " "scopes. For each such variable, a cell object is created to store the value; " -"the local variables of each stack frame that references the value contains a " +"the local variables of each stack frame that references the value contain a " "reference to the cells from outer scopes which also use that variable. When " "the value is accessed, the value contained in the cell is used instead of " "the cell object itself. This de-referencing of the cell object requires " "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 " -"referencia o valor contém uma referência para as células de escopos externos " +"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 " "objeto da célula requer suporte do código de bytes gerado; estes não são " diff --git a/c-api/code.po b/c-api/code.po index 87c7e2e58..f427ca1af 100644 --- a/c-api/code.po +++ b/c-api/code.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-27 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +63,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 +88,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 +96,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 +105,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 +116,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 +129,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 +139,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 +155,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 +165,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 +175,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 +195,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 +210,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 +220,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 +230,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 +242,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 +266,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 +278,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,23 +286,23 @@ 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 " +"*co* has been fully initialized. Otherwise, the callback is invoked before " "the destruction of *co* takes place, so the prior state of *co* can be " "inspected." msgstr "" "Se *evento* é ``PY_CODE_EVENT_CREATE``, então a função de retorno é invocada " -"após `co`ter sido completamente inicializado. Senão, a função de retorno é " -"invocada antes que a destruição de `co` ocorra, para que o estado anterior " +"após *co* ter sido completamente inicializado. Senão, a função de retorno é " +"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 +315,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 +331,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,23 +353,132 @@ 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:217 +msgid "Code Object Flags" +msgstr "Sinalizadores de objetos código" + +#: ../../c-api/code.rst:219 +msgid "" +"Code objects contain a bit-field of flags, which can be retrieved as the :" +"attr:`~codeobject.co_flags` Python attribute (for example using :c:func:" +"`PyObject_GetAttrString`), and set using a *flags* argument to :c:func:" +"`PyUnstable_Code_New` and similar functions." +msgstr "" +"Objetos código contêm um campo de bits de sinalizadores, que podem ser " +"recuperados como o atributo Python :attr:`~codeobject.co_flags` (por " +"exemplo, usando :c:func:`PyObject_GetAttrString`) e definidos usando um " +"argumento *flags* para :c:func:`PyUnstable_Code_New` e funções semelhantes." + +#: ../../c-api/code.rst:224 +msgid "" +"Flags whose names start with ``CO_FUTURE_`` correspond to features normally " +"selectable by :ref:`future statements `. These flags can be used in :" +"c:member:`PyCompilerFlags.cf_flags`. Note that many ``CO_FUTURE_`` flags are " +"mandatory in current versions of Python, and setting them has no effect." +msgstr "" +"Os sinalizadores cujos nomes começam com ``CO_FUTURE_`` correspondem a " +"recursos normalmente selecionáveis por :ref:`instruções future `. " +"Esses sinalizadores podem ser usados em :c:member:`PyCompilerFlags." +"cf_flags`. Observe que muitos sinalizadores ``CO_FUTURE_`` são obrigatórios " +"nas versões atuais do Python, e defini-los não tem efeito." + +#: ../../c-api/code.rst:230 +msgid "" +"The following flags are available. For their meaning, see the linked " +"documentation of their Python equivalents." +msgstr "" +"Os seguintes sinalizador estão disponíveis. Para saber o significado delas, " +"consulte a documentação vinculada de seus equivalentes em Python." + +#: ../../c-api/code.rst:238 +msgid "Flag" +msgstr "Sinalizador" -#: ../../c-api/code.rst:212 +#: ../../c-api/code.rst:239 +msgid "Meaning" +msgstr "Significado" + +#: ../../c-api/code.rst:241 +msgid ":py:data:`inspect.CO_OPTIMIZED`" +msgstr ":py:data:`inspect.CO_OPTIMIZED`" + +#: ../../c-api/code.rst:243 +msgid ":py:data:`inspect.CO_NEWLOCALS`" +msgstr ":py:data:`inspect.CO_NEWLOCALS`" + +#: ../../c-api/code.rst:245 +msgid ":py:data:`inspect.CO_VARARGS`" +msgstr ":py:data:`inspect.CO_VARARGS`" + +#: ../../c-api/code.rst:247 +msgid ":py:data:`inspect.CO_VARKEYWORDS`" +msgstr ":py:data:`inspect.CO_VARKEYWORDS`" + +#: ../../c-api/code.rst:249 +msgid ":py:data:`inspect.CO_NESTED`" +msgstr ":py:data:`inspect.CO_NESTED`" + +#: ../../c-api/code.rst:251 +msgid ":py:data:`inspect.CO_GENERATOR`" +msgstr ":py:data:`inspect.CO_GENERATOR`" + +#: ../../c-api/code.rst:253 +msgid ":py:data:`inspect.CO_COROUTINE`" +msgstr ":py:data:`inspect.CO_COROUTINE`" + +#: ../../c-api/code.rst:255 +msgid ":py:data:`inspect.CO_ITERABLE_COROUTINE`" +msgstr ":py:data:`inspect.CO_ITERABLE_COROUTINE`" + +#: ../../c-api/code.rst:257 +msgid ":py:data:`inspect.CO_ASYNC_GENERATOR`" +msgstr ":py:data:`inspect.CO_ASYNC_GENERATOR`" + +#: ../../c-api/code.rst:260 +msgid "no effect (:py:data:`__future__.division`)" +msgstr "sem efeito (:py:data:`__future__.division`)" + +#: ../../c-api/code.rst:262 +msgid "no effect (:py:data:`__future__.absolute_import`)" +msgstr "sem efeito (:py:data:`__future__.absolute_import`)" + +#: ../../c-api/code.rst:264 +msgid "no effect (:py:data:`__future__.with_statement`)" +msgstr "sem efeito (:py:data:`__future__.with_statement`)" + +#: ../../c-api/code.rst:266 +msgid "no effect (:py:data:`__future__.print_function`)" +msgstr "sem efeito (:py:data:`__future__.print_function`)" + +#: ../../c-api/code.rst:268 +msgid "no effect (:py:data:`__future__.unicode_literals`)" +msgstr "sem efeito (:py:data:`__future__.unicode_literals`)" + +#: ../../c-api/code.rst:270 +msgid "no effect (:py:data:`__future__.generator_stop`)" +msgstr "sem efeito (:py:data:`__future__.generator_stop`)" + +#: ../../c-api/code.rst:272 +msgid ":py:data:`__future__.annotations`" +msgstr ":py:data:`__future__.annotations`" + +#: ../../c-api/code.rst:276 msgid "Extra information" msgstr "Informação adicional" -#: ../../c-api/code.rst:214 +#: ../../c-api/code.rst:278 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 " "objects." msgstr "" -"Para suportar extensões de baixo nível de avaliação de quadro (frame), tais " -"como compiladores \"just-in-time\", é possível anexar dados arbitrários " -"adicionais a objetos código." +"Para oferece suporte a extensões de baixo nível de avaliação de quadro " +"(frame), tais 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:282 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 +488,13 @@ msgstr "" "um detalhe de implementação do CPython, e a API pode mudar sem avisos de " "descontinuidade." -#: ../../c-api/code.rst:224 -msgid "Return a new an opaque index value used to adding data to code objects." +#: ../../c-api/code.rst:288 +msgid "Return a new 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:290 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 +504,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:294 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 +514,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:300 msgid "as ``_PyEval_RequestCodeExtraIndex``" msgstr "como ``_PyEval_RequestCodeExtraIndex``" -#: ../../c-api/code.rst:240 +#: ../../c-api/code.rst:304 msgid "" "Renamed to ``PyUnstable_Eval_RequestCodeExtraIndex``. The old private name " "is deprecated, but will be available until the API changes." @@ -409,7 +526,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:310 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 +535,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:313 msgid "" "If no data was set under the index, set *extra* to ``NULL`` and return 0 " "without setting an exception." @@ -426,11 +543,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:318 msgid "as ``_PyCode_GetExtra``" msgstr "como ``_PyCode_GetExtra``" -#: ../../c-api/code.rst:258 +#: ../../c-api/code.rst:322 msgid "" "Renamed to ``PyUnstable_Code_GetExtra``. The old private name is deprecated, " "but will be available until the API changes." @@ -438,7 +555,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:328 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 +563,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:333 msgid "as ``_PyCode_SetExtra``" msgstr "como ``_PyCode_SetExtra``" -#: ../../c-api/code.rst:273 +#: ../../c-api/code.rst:337 msgid "" "Renamed to ``PyUnstable_Code_SetExtra``. The old private name is deprecated, " "but will be available until the API changes." @@ -470,22 +587,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:298 msgid "_PyEval_RequestCodeExtraIndex (C function)" msgstr "_PyEval_RequestCodeExtraIndex (função C)" -#: ../../c-api/code.rst:252 +#: ../../c-api/code.rst:316 msgid "_PyCode_GetExtra (C function)" msgstr "_PyCode_GetExtra (função C)" -#: ../../c-api/code.rst:267 +#: ../../c-api/code.rst:331 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..d50f5e2ff 100644 --- a/c-api/codec.po +++ b/c-api/codec.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,8 +34,9 @@ msgstr "Registra uma nova função de busca de codec." #: ../../c-api/codec.rst:10 msgid "" -"As side effect, this tries to load the :mod:`!encodings` package, if not yet " -"done, to make sure that it is always first in the list of search functions." +"As a side effect, this tries to load the :mod:`!encodings` package, if not " +"yet done, to make sure that it is always first in the list of search " +"functions." msgstr "" "Como efeito colateral, tenta carregar o pacote :mod:`!encodings`, se isso " "ainda não tiver sido feito, com o propósito de garantir que ele sempre seja " @@ -86,13 +86,13 @@ msgid "" "*object* is passed through the decoder function found for the given " "*encoding* using the error handling method defined by *errors*. *errors* " "may be ``NULL`` to use the default method defined for the codec. Raises a :" -"exc:`LookupError` if no encoder can be found." +"exc:`LookupError` if no decoder can be found." msgstr "" "*object* é passado através da função de decodificação encontrada para a " "codificação fornecida por meio de *encoding*, usando o método de tratamento " "de erros definido por *errors*. *errors* pode ser ``NULL`` para usar o " "método padrão definido para o codec. Levanta um :exc:`LookupError` se nenhum " -"codificador puder ser encontrado." +"decodificador puder ser encontrado." #: ../../c-api/codec.rst:46 msgid "Codec lookup API" @@ -226,3 +226,15 @@ msgstr "" #: ../../c-api/codec.rst:129 msgid "Replace the unicode encode error with ``\\N{...}`` escapes." msgstr "Substitui os erros de codificação unicode com escapes ``\\N{...}``." + +#: ../../c-api/codec.rst:135 +msgid "Codec utility variables" +msgstr "Variáveis utilitárias de codec" + +#: ../../c-api/codec.rst:139 +msgid "" +"A string constant containing the lowercase hexadecimal digits: " +"``\"0123456789abcdef\"``." +msgstr "" +"Uma constante string contendo os dígitos hexadecimais minúsculos: " +"``\"0123456789abcdef\"``." diff --git a/c-api/complex.po b/c-api/complex.po index 9d8cc6d8b..76ddba1b8 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..a2dea25ad 100644 --- a/c-api/concrete.po +++ b/c-api/concrete.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,12 +92,16 @@ 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" msgstr "Outros Objetos" +#: ../../c-api/concrete.rst:122 +msgid "C API for extension modules" +msgstr "API C para módulos de extensão" + #: ../../c-api/concrete.rst:43 ../../c-api/concrete.rst:58 #: ../../c-api/concrete.rst:80 msgid "object" diff --git a/c-api/contextvars.po b/c-api/contextvars.po index 821ce8863..4e496d407 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..f3f4e5112 100644 --- a/c-api/conversion.po +++ b/c-api/conversion.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,11 +109,11 @@ msgstr "" #: ../../c-api/conversion.rst:44 msgid "" -"When ``rv < 0``, \"something bad happened.\" ``str[size-1]`` is ``'\\0'`` in " -"this case too, but the rest of *str* is undefined. The exact cause of the " -"error depends on the underlying platform." +"When ``rv < 0``, the output conversion failed and ``str[size-1]`` is " +"``'\\0'`` in this case too, but the rest of *str* is undefined. The exact " +"cause of the error depends on the underlying platform." msgstr "" -"Quando ``rv < 0``, \"aconteceu algo de errado.\" ``str[size-1]`` é ``'\\0'`` " +"Quando ``rv < 0``, a conversão da saída falhou e ``str[size-1]`` é ``'\\0'`` " "neste caso também, mas o resto de *str* é indefinido. A causa exata do erro " "depende da plataforma subjacente." @@ -270,39 +271,30 @@ msgstr "" "func:`repr`." #: ../../c-api/conversion.rst:131 -msgid "" -"*flags* can be zero or more of the values ``Py_DTSF_SIGN``, " -"``Py_DTSF_ADD_DOT_0``, or ``Py_DTSF_ALT``, or-ed together:" +msgid "*flags* can be zero or more of the following values or-ed together:" msgstr "" -"*flags* pode ser zero ou mais de valores ``Py_DTSF_SIGN``, " -"``Py_DTSF_ADD_DOT_0`` ou ``Py_DTSF_ALT``, alternados por operador lógico OU:" -#: ../../c-api/conversion.rst:134 +#: ../../c-api/conversion.rst:135 msgid "" -"``Py_DTSF_SIGN`` means to always precede the returned string with a sign " -"character, even if *val* is non-negative." +"Always precede the returned string with a sign character, even if *val* is " +"non-negative." msgstr "" -"``Py_DTSF_SIGN`` significa sempre preceder a string retornada com um " -"caractere de sinal, mesmo se *val* não for negativo." -#: ../../c-api/conversion.rst:137 -msgid "" -"``Py_DTSF_ADD_DOT_0`` means to ensure that the returned string will not look " -"like an integer." +#: ../../c-api/conversion.rst:140 +msgid "Ensure that the returned string will not look like an integer." msgstr "" -"``Py_DTSF_ADD_DOT_0`` significa garantir que a string retornada não se " -"pareça com um inteiro." -#: ../../c-api/conversion.rst:140 +#: ../../c-api/conversion.rst:144 msgid "" -"``Py_DTSF_ALT`` means to apply \"alternate\" formatting rules. See the " -"documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for details." +"Apply \"alternate\" formatting rules. See the documentation for the :c:func:" +"`PyOS_snprintf` ``'#'`` specifier for details." msgstr "" -"``Py_DTSF_ALT`` significa aplicar regras de formatação \"alternativas\". " -"Veja a documentação para o especificador ``'#'`` de :c:func:`PyOS_snprintf` " -"para detalhes." -#: ../../c-api/conversion.rst:144 +#: ../../c-api/conversion.rst:150 +msgid "Negative zero is converted to positive zero." +msgstr "" + +#: ../../c-api/conversion.rst:154 msgid "" "If *ptype* is non-``NULL``, then the value it points to will be set to one " "of ``Py_DTST_FINITE``, ``Py_DTST_INFINITE``, or ``Py_DTST_NAN``, signifying " @@ -314,7 +306,7 @@ msgstr "" "``Py_DTST_NAN``, significando que *val* é um número finito, um número " "infinito ou não um número, respectivamente." -#: ../../c-api/conversion.rst:148 +#: ../../c-api/conversion.rst:158 msgid "" "The return value is a pointer to *buffer* with the converted string or " "``NULL`` if the conversion failed. The caller is responsible for freeing the " @@ -324,7 +316,7 @@ msgstr "" "``NULL`` se a conversão falhou. O chamador é responsável por liberar a " "string retornada chamando :c:func:`PyMem_Free`." -#: ../../c-api/conversion.rst:157 +#: ../../c-api/conversion.rst:167 msgid "" "Case insensitive comparison of strings. The function works almost " "identically to :c:func:`!strcmp` except that it ignores the case." @@ -333,7 +325,7 @@ msgstr "" "funciona quase de forma idêntica a :c:func:`!strcmp` exceto que ignora a " "diferença entre maiúsculas e minúsculas." -#: ../../c-api/conversion.rst:163 +#: ../../c-api/conversion.rst:173 msgid "" "Case insensitive comparison of strings. The function works almost " "identically to :c:func:`!strncmp` except that it ignores the case." @@ -341,3 +333,57 @@ msgstr "" "Comparação de strings sem diferença entre maiúsculas e minúsculas. A função " "funciona quase de forma idêntica a :c:func:`!strncmp` exceto que ignora a " "diferença entre maiúsculas e minúsculas." + +#: ../../c-api/conversion.rst:178 +msgid "Character classification and conversion" +msgstr "" + +#: ../../c-api/conversion.rst:180 +msgid "" +"The following macros provide locale-independent (unlike the C standard " +"library ``ctype.h``) character classification and conversion. The argument " +"must be a signed or unsigned :c:expr:`char`." +msgstr "" + +#: ../../c-api/conversion.rst:187 +msgid "Return true if the character *c* is an alphanumeric character." +msgstr "" + +#: ../../c-api/conversion.rst:192 +msgid "" +"Return true if the character *c* is an alphabetic character (``a-z`` and ``A-" +"Z``)." +msgstr "" + +#: ../../c-api/conversion.rst:197 +msgid "Return true if the character *c* is a decimal digit (``0-9``)." +msgstr "" + +#: ../../c-api/conversion.rst:202 +msgid "Return true if the character *c* is a lowercase ASCII letter (``a-z``)." +msgstr "" + +#: ../../c-api/conversion.rst:207 +msgid "" +"Return true if the character *c* is an uppercase ASCII letter (``A-Z``)." +msgstr "" + +#: ../../c-api/conversion.rst:212 +msgid "" +"Return true if the character *c* is a whitespace character (space, tab, " +"carriage return, newline, vertical tab, or form feed)." +msgstr "" + +#: ../../c-api/conversion.rst:218 +msgid "" +"Return true if the character *c* is a hexadecimal digit (``0-9``, ``a-f``, " +"and ``A-F``)." +msgstr "" + +#: ../../c-api/conversion.rst:224 +msgid "Return the lowercase equivalent of the character *c*." +msgstr "" + +#: ../../c-api/conversion.rst:229 +msgid "Return the uppercase equivalent of the character *c*." +msgstr "" diff --git a/c-api/coro.po b/c-api/coro.po index 3b617dc55..f188fc30b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/curses.po b/c-api/curses.po new file mode 100644 index 000000000..deb38ccdd --- /dev/null +++ b/c-api/curses.po @@ -0,0 +1,250 @@ +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-11-11 15: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" +"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " +"1000000 == 0 ? 1 : 2;\n" + +#: ../../c-api/curses.rst:4 +msgid "Curses C API" +msgstr "API C de curses" + +#: ../../c-api/curses.rst:6 +msgid "" +":mod:`curses` exposes a small C interface for extension modules. Consumers " +"must include the header file :file:`py_curses.h` (which is not included by " +"default by :file:`Python.h`) and :c:func:`import_curses` must be invoked, " +"usually as part of the module initialisation function, to populate :c:var:" +"`PyCurses_API`." +msgstr "" +":mod:`curses` expõe uma pequena interface C para módulos de extensão. Os " +"usuários devem incluir o arquivo de cabeçalho :file:`py_curses.h` (que não é " +"incluído por padrão em :file:`Python.h`) e :c:func:`import_curses` deve ser " +"invocada, geralmente como parte da função de inicialização do módulo, para " +"popular :c:var:`PyCurses_API`." + +#: ../../c-api/curses.rst:14 +msgid "" +"Neither the C API nor the pure Python :mod:`curses` module are compatible " +"with subinterpreters." +msgstr "" +"Nem a API C nem o módulo :mod:`curses` do Python puro são compatíveis com " +"subinterpretadores." + +#: ../../c-api/curses.rst:19 +msgid "" +"Import the curses C API. The macro does not need a semi-colon to be called." +msgstr "" +"Importa a API C do curses. A macro não precisa de ponto e vírgula para ser " +"chamada." + +#: ../../c-api/curses.rst:21 +msgid "On success, populate the :c:var:`PyCurses_API` pointer." +msgstr "Em caso de sucesso, popula o ponteiro :c:var:`PyCurses_API`." + +#: ../../c-api/curses.rst:23 +msgid "" +"On failure, set :c:var:`PyCurses_API` to NULL and set an exception. The " +"caller must check if an error occurred via :c:func:`PyErr_Occurred`:" +msgstr "" +"Em caso de falha, define :c:var:`PyCurses_API` como NULL e levanta uma " +"exceção. O chamador deve verificar se ocorreu um erro através de :c:func:" +"`PyErr_Occurred`:" + +#: ../../c-api/curses.rst:26 +msgid "" +"import_curses(); // semi-colon is optional but recommended\n" +"if (PyErr_Occurred()) { /* cleanup */ }" +msgstr "" +"import_curses(); // O ponto e vírgula é opcional, mas recomendado.\n" +"if (PyErr_Occurred()) { /* cleanup */ }" + +#: ../../c-api/curses.rst:34 +msgid "" +"Dynamically allocated object containing the curses C API. This variable is " +"only available once :c:macro:`import_curses` succeeds." +msgstr "" +"Objeto alocado dinamicamente contendo a API C do curses. Esta variável só " +"estará disponível após a execução bem-sucedida da macro :c:macro:" +"`import_curses`." + +#: ../../c-api/curses.rst:37 +msgid "``PyCurses_API[0]`` corresponds to :c:data:`PyCursesWindow_Type`." +msgstr "``PyCurses_API[0]`` corresponde a :c:data:`PyCursesWindow_Type`." + +#: ../../c-api/curses.rst:39 +msgid "" +"``PyCurses_API[1]``, ``PyCurses_API[2]``, and ``PyCurses_API[3]`` are " +"pointers to predicate functions of type ``int (*)(void)``." +msgstr "" +"``PyCurses_API[1]``, ``PyCurses_API[2]`` e ``PyCurses_API[3]`` são ponteiros " +"para funções predicativas do tipo ``int (*)(void)``." + +#: ../../c-api/curses.rst:42 +msgid "" +"When called, these predicates return whether :func:`curses.setupterm`, :func:" +"`curses.initscr`, and :func:`curses.start_color` have been called " +"respectively." +msgstr "" +"Quando chamados, esses predicados retornam se :func:`curses.setupterm`, :" +"func:`curses.initscr` e :func:`curses.start_color` foram chamados, " +"respectivamente." + +#: ../../c-api/curses.rst:46 +msgid "" +"See also the convenience macros :c:macro:`PyCursesSetupTermCalled`, :c:macro:" +"`PyCursesInitialised`, and :c:macro:`PyCursesInitialisedColor`." +msgstr "" +"Veja também as macros de conveniência :c:macro:`PyCursesSetupTermCalled`, :c:" +"macro:`PyCursesInitialised` e :c:macro:`PyCursesInitialisedColor`." + +#: ../../c-api/curses.rst:51 +msgid "" +"The number of entries in this structure is subject to changes. Consider " +"using :c:macro:`PyCurses_API_pointers` to check if new fields are available " +"or not." +msgstr "" +"O número de entradas nesta estrutura está sujeito a alterações. Considere " +"usar :c:macro:`PyCurses_API_pointers` para verificar se novos campos estão " +"disponíveis." + +#: ../../c-api/curses.rst:58 +msgid "" +"The number of accessible fields (``4``) in :c:var:`PyCurses_API`. This " +"number is incremented whenever new fields are added." +msgstr "" +"O número de campos acessíveis (``4``) em :c:var:`PyCurses_API`. Esse número " +"é incrementado sempre que novos campos são adicionados." + +#: ../../c-api/curses.rst:64 +msgid "" +"The :ref:`heap type ` corresponding to :class:`curses.window`." +msgstr "" +"O :ref:`tipo de heap ` correspondente a :class:`curses.window`." + +#: ../../c-api/curses.rst:69 +msgid "" +"Return true if *op* is a :class:`curses.window` instance, false otherwise." +msgstr "" +"Retorna verdadeiro se *op* for uma instância de :class:`curses.window`, " +"falso caso contrário." + +#: ../../c-api/curses.rst:72 +msgid "" +"The following macros are convenience macros expanding into C statements. In " +"particular, they can only be used as ``macro;`` or ``macro``, but not " +"``macro()`` or ``macro();``." +msgstr "" +"As macros a seguir são macros de conveniência que se expandem em instruções " +"C. Em particular, elas só podem ser usadas como ``macro;`` ou ``macro``, mas " +"não como ``macro()`` ou ``macro();``." + +#: ../../c-api/curses.rst:78 +msgid "Macro checking if :func:`curses.setupterm` has been called." +msgstr "Macro que verifica se :func:`curses.setupterm` foi chamada." + +#: ../../c-api/curses.rst:80 ../../c-api/curses.rst:97 +#: ../../c-api/curses.rst:114 +msgid "The macro expansion is roughly equivalent to:" +msgstr "A expansão de macro é aproximadamente equivalente a:" + +#: ../../c-api/curses.rst:82 +msgid "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_setupterm_called = (predicate_t)PyCurses_API[1];\n" +" if (!was_setupterm_called()) {\n" +" return NULL;\n" +" }\n" +"}" +msgstr "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_setupterm_called = (predicate_t)PyCurses_API[1];\n" +" if (!was_setupterm_called()) {\n" +" return NULL;\n" +" }\n" +"}" + +#: ../../c-api/curses.rst:95 +msgid "Macro checking if :func:`curses.initscr` has been called." +msgstr "Macro que verifica se :func:`curses.initscr` foi chamada." + +#: ../../c-api/curses.rst:99 +msgid "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_initscr_called = (predicate_t)PyCurses_API[2];\n" +" if (!was_initscr_called()) {\n" +" return NULL;\n" +" }\n" +"}" +msgstr "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_initscr_called = (predicate_t)PyCurses_API[2];\n" +" if (!was_initscr_called()) {\n" +" return NULL;\n" +" }\n" +"}" + +#: ../../c-api/curses.rst:112 +msgid "Macro checking if :func:`curses.start_color` has been called." +msgstr "Macro que verifica se :func:`curses.start_color` foi chamada." + +#: ../../c-api/curses.rst:116 +msgid "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_start_color_called = (predicate_t)PyCurses_API[3];\n" +" if (!was_start_color_called()) {\n" +" return NULL;\n" +" }\n" +"}" +msgstr "" +"{\n" +" typedef int (*predicate_t)(void);\n" +" predicate_t was_start_color_called = (predicate_t)PyCurses_API[3];\n" +" if (!was_start_color_called()) {\n" +" return NULL;\n" +" }\n" +"}" + +#: ../../c-api/curses.rst:128 +msgid "Internal data" +msgstr "Dados internos" + +#: ../../c-api/curses.rst:130 +msgid "" +"The following objects are exposed by the C API but should be considered " +"internal-only." +msgstr "" +"Os seguintes objetos são expostos pela API C, mas devem ser considerados " +"apenas para uso interno." + +#: ../../c-api/curses.rst:135 +msgid "Name of the curses capsule to pass to :c:func:`PyCapsule_Import`." +msgstr "" +"Nome da cápsula do curses a ser passada para :c:func:`PyCapsule_Import`." + +#: ../../c-api/curses.rst:137 +msgid "Internal usage only. Use :c:macro:`import_curses` instead." +msgstr "Uso interno apenas. Use :c:macro:`import_curses` em vez disso." diff --git a/c-api/datetime.po b/c-api/datetime.po index 87149f4a9..31ae712b1 100644 --- a/c-api/datetime.po +++ b/c-api/datetime.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,55 +38,81 @@ 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 "" -"This instance of :c:type:`PyTypeObject` represents Python type for the " +"This instance of :c:type:`PyTypeObject` represents the Python type for the " "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 +136,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 +154,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 +172,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 +190,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 +208,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 +298,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 +321,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 +355,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 +365,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 +388,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..b2f14753d 100644 --- a/c-api/descriptor.po +++ b/c-api/descriptor.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,10 +42,58 @@ msgstr "O tipo de objeto para os tipos de descritores embutidos." #: ../../c-api/descriptor.rst:35 msgid "" -"Return non-zero if the descriptor objects *descr* describes a data " -"attribute, or ``0`` if it describes a method. *descr* must be a descriptor " -"object; there is no error checking." +"Return non-zero if the descriptor object *descr* describes a data attribute, " +"or ``0`` if it describes a method. *descr* must be a descriptor object; " +"there is no error checking." msgstr "" -"Retorna não-zero se os objetos descritores *descr* descrevem um atributo de " +"Retorna não-zero se o objeto descritor *descr* descrevem um atributo de " "dados, ou ``0`` se os mesmos descrevem um método. *descr* deve ser um objeto " "descritor; não há verificação de erros." + +#: ../../c-api/descriptor.rst:44 +msgid "Built-in descriptors" +msgstr "" + +#: ../../c-api/descriptor.rst:48 +msgid "" +"The type object for super objects. This is the same object as :class:`super` " +"in the Python layer." +msgstr "" + +#: ../../c-api/descriptor.rst:54 +msgid "" +"The type of class method objects. This is the same object as :class:" +"`classmethod` in the Python layer." +msgstr "" + +#: ../../c-api/descriptor.rst:60 +msgid "" +"Create a new :class:`classmethod` object wrapping *callable*. *callable* " +"must be a callable object and must not be ``NULL``." +msgstr "" + +#: ../../c-api/descriptor.rst:63 +msgid "" +"On success, this function returns a :term:`strong reference` to a new class " +"method descriptor. On failure, this function returns ``NULL`` with an " +"exception set." +msgstr "" + +#: ../../c-api/descriptor.rst:70 +msgid "" +"The type of static method objects. This is the same object as :class:" +"`staticmethod` in the Python layer." +msgstr "" + +#: ../../c-api/descriptor.rst:76 +msgid "" +"Create a new :class:`staticmethod` object wrapping *callable*. *callable* " +"must be a callable object and must not be ``NULL``." +msgstr "" + +#: ../../c-api/descriptor.rst:79 +msgid "" +"On success, this function returns a :term:`strong reference` to a new static " +"method descriptor. On failure, this function returns ``NULL`` with an " +"exception set." +msgstr "" diff --git a/c-api/dict.po b/c-api/dict.po index c275b56f9..f5d248e27 100644 --- a/c-api/dict.po +++ b/c-api/dict.po @@ -1,28 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,13 +79,13 @@ msgstr "Esvazia um dicionário existente de todos os pares chave-valor." #: ../../c-api/dict.rst:53 msgid "" -"Determine if dictionary *p* contains *key*. If an item in *p* is matches " +"Determine if dictionary *p* contains *key*. If an item in *p* matches " "*key*, return ``1``, otherwise return ``0``. On error, return ``-1``. This " "is equivalent to the Python expression ``key in p``." msgstr "" "Determina se o dicionário *p* contém *key*. Se um item em *p* corresponder à " "*key*, retorna ``1``, caso contrário, retorna ``0``. Em caso de erro, " -"retorna ``-1``. Isso é equivalente à expressão Python ``key in p``." +"retorna ``-1``. Isso equivale à expressão Python ``key in p``." #: ../../c-api/dict.rst:60 msgid "" @@ -239,9 +237,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:" @@ -298,7 +295,7 @@ msgstr "" #: ../../c-api/dict.rst:200 msgid "" "Remove *key* from dictionary *p* and optionally return the removed value. Do " -"not raise :exc:`KeyError` if the key missing." +"not raise :exc:`KeyError` if the key is missing." msgstr "" "Remove *key* do dicionário *p* e, opcionalmente, retorna o valor removido. " "Não levanta :exc:`KeyError` se a chave estiver ausente." @@ -321,11 +318,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 is 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 "" @@ -365,6 +362,10 @@ msgstr "" "um dicionário." #: ../../c-api/dict.rst:250 +msgid "Similar to :c:func:`PyDict_Size`, but without error checking." +msgstr "Similar a :c:func:`PyDict_Size`, mas sem verificação de erro." + +#: ../../c-api/dict.rst:255 msgid "" "Iterate over all key-value pairs in the dictionary *p*. The :c:type:" "`Py_ssize_t` referred to by *ppos* must be initialized to ``0`` prior to the " @@ -388,11 +389,29 @@ msgstr "" "Seu valor representa deslocamentos dentro da estrutura do dicionário interno " "e, como a estrutura é esparsa, os deslocamentos não são consecutivos." -#: ../../c-api/dict.rst:261 +#: ../../c-api/dict.rst:266 msgid "For example::" msgstr "Por exemplo::" -#: ../../c-api/dict.rst:271 +#: ../../c-api/dict.rst:268 +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:276 msgid "" "The dictionary *p* should not be mutated during iteration. It is safe to " "modify the values of the keys as you iterate over the dictionary, but only " @@ -402,7 +421,45 @@ 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:293 +#: ../../c-api/dict.rst:280 +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:298 msgid "" "The function is not thread-safe in the :term:`free-threaded ` build without external synchronization. You can use :c:macro:" @@ -413,7 +470,21 @@ msgstr "" "`Py_BEGIN_CRITICAL_SECTION` para travar o dicionário enquanto itera sobre " "ele::" -#: ../../c-api/dict.rst:307 +#: ../../c-api/dict.rst:303 +msgid "" +"Py_BEGIN_CRITICAL_SECTION(self->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:312 msgid "" "Iterate over mapping object *b* adding key-value pairs to dictionary *a*. " "*b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys` " @@ -430,7 +501,7 @@ msgstr "" "adicionados apenas se não houver uma chave correspondente em *a*. Retorna " "``0`` em caso de sucesso ou ``-1`` se uma exceção foi levantada." -#: ../../c-api/dict.rst:317 +#: ../../c-api/dict.rst:322 msgid "" "This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to ``a." "update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall back " @@ -444,7 +515,7 @@ msgstr "" "argumento não tiver o atributo \"keys\". Retorna ``0`` em caso de sucesso ou " "``-1`` se uma exceção foi levantada." -#: ../../c-api/dict.rst:326 +#: ../../c-api/dict.rst:331 msgid "" "Update or merge into dictionary *a*, from the key-value pairs in *seq2*. " "*seq2* must be an iterable object producing iterable objects of length 2, " @@ -459,7 +530,19 @@ 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:340 +#: ../../c-api/dict.rst:338 +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:345 msgid "" "Register *callback* as a dictionary watcher. Return a non-negative integer " "id which must be passed to future calls to :c:func:`PyDict_Watch`. In case " @@ -471,7 +554,7 @@ msgstr "" "`PyDict_Watch`. Em caso de erro (por exemplo, não há mais IDs de observador " "disponíveis), retorna ``-1`` e define uma exceção." -#: ../../c-api/dict.rst:349 +#: ../../c-api/dict.rst:354 msgid "" "Clear watcher identified by *watcher_id* previously returned from :c:func:" "`PyDict_AddWatcher`. Return ``0`` on success, ``-1`` on error (e.g. if the " @@ -481,7 +564,7 @@ msgstr "" "c:func:`PyDict_AddWatcher`. Retorna ``0`` em caso de sucesso, ``-1`` em caso " "de erro (por exemplo, se o *watcher_id* fornecido nunca foi registrado)." -#: ../../c-api/dict.rst:357 +#: ../../c-api/dict.rst:362 msgid "" "Mark dictionary *dict* as watched. The callback granted *watcher_id* by :c:" "func:`PyDict_AddWatcher` will be called when *dict* is modified or " @@ -492,7 +575,7 @@ msgstr "" "modificado ou desalocado. Retorna ``0`` em caso de sucesso ou ``-1`` em caso " "de erro." -#: ../../c-api/dict.rst:365 +#: ../../c-api/dict.rst:370 msgid "" "Mark dictionary *dict* as no longer watched. The callback granted " "*watcher_id* by :c:func:`PyDict_AddWatcher` will no longer be called when " @@ -505,7 +588,7 @@ msgstr "" "anteriormente por este observador. Retorna ``0`` em caso de sucesso ou " "``-1`` em caso de erro." -#: ../../c-api/dict.rst:374 +#: ../../c-api/dict.rst:379 msgid "" "Enumeration of possible dictionary watcher events: ``PyDict_EVENT_ADDED``, " "``PyDict_EVENT_MODIFIED``, ``PyDict_EVENT_DELETED``, " @@ -517,11 +600,11 @@ msgstr "" "``PyDict_EVENT_CLONED``, ``PyDict_EVENT_CLEARED`` ou " "``PyDict_EVENT_DEALLOCATED``." -#: ../../c-api/dict.rst:382 +#: ../../c-api/dict.rst:387 msgid "Type of a dict watcher callback function." msgstr "Tipo de uma função de retorno de chamada de observador de dicionário." -#: ../../c-api/dict.rst:384 +#: ../../c-api/dict.rst:389 msgid "" "If *event* is ``PyDict_EVENT_CLEARED`` or ``PyDict_EVENT_DEALLOCATED``, both " "*key* and *new_value* will be ``NULL``. If *event* is ``PyDict_EVENT_ADDED`` " @@ -535,7 +618,7 @@ msgstr "" "valor de *key*. Se *event* for ``PyDict_EVENT_DELETED``, *key* estará sendo " "excluída do dicionário e *new_value* será ``NULL``." -#: ../../c-api/dict.rst:390 +#: ../../c-api/dict.rst:395 msgid "" "``PyDict_EVENT_CLONED`` occurs when *dict* was previously empty and another " "dict is merged into it. To maintain efficiency of this operation, per-key " @@ -548,7 +631,7 @@ msgstr "" "disso, um único ``PyDict_EVENT_CLONED`` é emitido e *key* será o dicionário " "de origem." -#: ../../c-api/dict.rst:396 +#: ../../c-api/dict.rst:401 msgid "" "The callback may inspect but must not modify *dict*; doing so could have " "unpredictable effects, including infinite recursion. Do not trigger Python " @@ -559,7 +642,7 @@ msgstr "" "execução do código Python na função de retorno, pois isso poderia modificar " "o dict como um efeito colateral." -#: ../../c-api/dict.rst:400 +#: ../../c-api/dict.rst:405 msgid "" "If *event* is ``PyDict_EVENT_DEALLOCATED``, taking a new reference in the " "callback to the about-to-be-destroyed dictionary will resurrect it and " @@ -573,7 +656,7 @@ msgstr "" "ressuscitado for destruído mais tarde, quaisquer funções de retorno do " "observador ativos naquele momento serão chamados novamente." -#: ../../c-api/dict.rst:406 +#: ../../c-api/dict.rst:411 msgid "" "Callbacks occur before the notified modification to *dict* takes place, so " "the prior state of *dict* can be inspected." @@ -581,17 +664,17 @@ msgstr "" "As funções de retorno ocorrem antes que a modificação notificada no *dict* " "ocorra, de modo que o estado anterior do *dict* possa ser inspecionado." -#: ../../c-api/dict.rst:409 +#: ../../c-api/dict.rst:414 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/dict.rst:413 +#: ../../c-api/dict.rst:418 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 " @@ -603,7 +686,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..e1cbb44e9 100644 --- a/c-api/exceptions.po +++ b/c-api/exceptions.po @@ -1,42 +1,34 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Joao Roccella , 2025 +# Gustavo Reis, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/exceptions.rst:8 msgid "Exception Handling" -msgstr "Manipulando Exceções" +msgstr "Tratamento de exceções" #: ../../c-api/exceptions.rst:10 msgid "" @@ -52,13 +44,13 @@ msgid "" msgstr "" "As funções descritas nesse capítulo permitem você tratar e gerar exceções em " "Python. É importante entender alguns princípios básicos no tratamento de " -"exceção no Python. Funciona de forma parecida com a variável POSIX :c:data:" +"exceções no Python. Funciona de forma parecida com a variável POSIX :c:data:" "`errno`: existe um indicador global (por thread) do último erro ocorrido. A " -"maioria das funções da API C não limpa isso com êxito, mas indica a causa do " -"erro na falha. A maioria das funções da API retorna um indicador de erro, " -"geralmente, ``NULL`` se eles devem retornar um ponteiro, ou ``-1`` se " -"retornarem um inteiro (exceção: as funções ``PyArg_*`` retornam ``1`` para " -"sucesso e ``0`` para falha)." +"maioria das funções da API C não o zera ao obter sucesso, mas o define para " +"indicar a causa do erro ao falhar. A maioria das funções da API retorna um " +"indicador de erro, geralmente, ``NULL`` se eles devem retornar um ponteiro, " +"ou ``-1`` se retornarem um inteiro (exceção: as funções ``PyArg_*`` retornam " +"``1`` para sucesso e ``0`` para falha)." #: ../../c-api/exceptions.rst:20 msgid "" @@ -68,8 +60,8 @@ msgid "" "forbidden, for example you can't have a non-``NULL`` traceback if the " "exception type is ``NULL``)." msgstr "" -"Concretamente, o indicador de erro consiste em três ponteiros de objeto: o " -"tipo da exceção, o valor da exceção e o objeto de traceback. Qualquer um " +"De forma concreta, o indicador de erro consiste em três ponteiros de objeto: " +"o tipo da exceção, o valor da exceção e o objeto de traceback. Qualquer um " "desses ponteiros pode ser ``NULL`` se não definido (embora algumas " "combinações sejam proibidas, por exemplo, você não pode ter um retorno não " "``NULL`` se o tipo de exceção for ``NULL``)." @@ -99,14 +91,14 @@ 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 " +"O indicador de erro **não** é 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 @@ -128,6 +120,10 @@ msgid "" "printed and the Python process will exit with the error code specified by " "the ``SystemExit`` instance." msgstr "" +"Exibe um traceback padrão para ``sys.stderr`` e limpe o indicador de erro. " +"**A menos que** o erro seja um ``SystemExit``, nesse caso, nenhum traceback " +"será impresso e o processo Python será encerrado com o código de erro " +"especificado pela instância ``SystemExit``." #: ../../c-api/exceptions.rst:60 msgid "" @@ -145,10 +141,15 @@ msgid "" "last_traceback` are also set to the type, value and traceback of this " "exception, respectively." msgstr "" +"Se *set_sys_last_vars* for diferente de zero, a variável :data:`sys." +"last_exc` será definida com a exceção exibida. Para manter a " +"retrocompatibilidade, as variáveis descontinuadas :data:`sys.last_type`, :" +"data:`sys.last_value` e :data:`sys.last_traceback` também serão definidas " +"com o tipo, valor e traceback dessa exceção, respectivamente." #: ../../c-api/exceptions.rst:69 msgid "The setting of :data:`sys.last_exc` was added." -msgstr "" +msgstr "A configuração de :data:`sys.last_exc` foi adicionada." #: ../../c-api/exceptions.rst:75 msgid "Alias for ``PyErr_PrintEx(1)``." @@ -168,6 +169,10 @@ msgid "" "raise the exception. It is used, for example, when an exception occurs in " "an :meth:`~object.__del__` method." msgstr "" +"Esta função utilitária imprime uma mensagem de aviso para ``sys.stderr`` " +"quando uma exceção foi definida, mas é impossível para o interpretador " +"realmente gerar a exceção. É usada, por exemplo, quando ocorre uma exceção " +"em um método :meth:`~object.__del__`." #: ../../c-api/exceptions.rst:88 msgid "" @@ -176,6 +181,10 @@ msgid "" "*obj* will be printed in the warning message. If *obj* is ``NULL``, only the " "traceback is printed." msgstr "" +"A função é chamada com um único argumento *obj* que identifica o contexto em " +"que ocorreu a exceção não gerável. Se possível, o repr de *obj* será " +"impresso na mensagem de aviso. Se *obj* for ``NULL``, apenas o traceback " +"será impresso." #: ../../c-api/exceptions.rst:93 msgid "An exception must be set when calling this function." @@ -199,16 +208,24 @@ msgid "" "is roughly equivalent to ``PyErr_FormatUnraisable(\"Exception ignored in: " "%R\", obj)``. If *format* is ``NULL``, only the traceback is printed." msgstr "" +"Similar a :c:func:`PyErr_WriteUnraisable`, mas *format* e parâmetros " +"subsequentes ajudam a formatar a mensagem de aviso; eles têm o mesmo " +"significado e valores que em :c:func:`PyUnicode_FromFormat`. " +"``PyErr_WriteUnraisable(obj)`` é aproximadamente equivalente à " +"``PyErr_FormatUnraisable(\"Exception ignored in: %R\", obj)``. Se *format* é " +"``NULL``, somente o rastreamento é impresso." #: ../../c-api/exceptions.rst:116 msgid "" "Print the standard traceback display of ``exc`` to ``sys.stderr``, including " "chained exceptions and notes." msgstr "" +"Imprime a exibição padrão do traceback de ``exc`` em ``sys.stderr``, " +"incluindo as exceções encadeadas e notas." #: ../../c-api/exceptions.rst:123 msgid "Raising exceptions" -msgstr "Lançando exceções" +msgstr "Levantando exceções" #: ../../c-api/exceptions.rst:125 msgid "" @@ -228,6 +245,11 @@ msgid "" "reference` to it (e.g. with :c:func:`Py_INCREF`). The second argument is an " "error message; it is decoded from ``'utf-8'``." msgstr "" +"Esse é o modo mais comum de definir o indicador de erro. O primeiro " +"argumento especifica o tipo da exceção; é normalmente uma das exceções " +"padrão, como :c:data:`PyExc_RuntimeError`. Você não precisa criar um novo :" +"term:`strong reference` para ela (como em :c:func:`Py_INCREF`). O segundo " +"argumento é uma mensagem de erro; ela é codificada com ``'utf-8'``." #: ../../c-api/exceptions.rst:141 msgid "" @@ -244,6 +266,11 @@ msgid "" "help format the error message; they have the same meaning and values as in :" "c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded string." msgstr "" +"Essa função define o indicador de erro e retorna ``NULL``. *exception* deve " +"ser uma classe Python de exceção. O *format* e parâmetros subsequentes " +"ajudam a formatar a mensagem de erro; eles têm o mesmo significado e valores " +"que em :c:func:`PyUnicode_FromFormat`. *format* é uma string codificada em " +"ASCII." #: ../../c-api/exceptions.rst:156 msgid "" @@ -263,6 +290,9 @@ msgid "" "*message* indicates that a built-in operation was invoked with an illegal " "argument. It is mostly for internal use." msgstr "" +"Essa é uma abreviação de ``PyErr_SetString(PyExc_TypeError, message)``, na " +"qual *message* indica que uma operação embutida foi invocada com um " +"argumento ilegal. Ela é principalmente para uso interno." #: ../../c-api/exceptions.rst:176 msgid "" @@ -287,6 +317,17 @@ msgid "" "returns ``NULL``, so a wrapper function around a system call can write " "``return PyErr_SetFromErrno(type);`` when the system call returns an error." msgstr "" +"Esta é uma função conveniente para levantar uma exceção quando uma função da " +"biblioteca C retornou um erro e definir a variável C :c:data:`errno`. Ela " +"constrói um objeto tupla cujo primeiro item é o valor inteiro :c:data:" +"`errno` e cujo segundo item é a mensagem de erro correspondente (obtida de :" +"c:func:`!strerror`), e então chama ``PyErr_SetObject(type, object)``. No " +"Unix, quando o valor :c:data:`errno` é :c:macro:`!EINTR`, indicando uma " +"chamada de sistema interrompida, isso chama :c:func:`PyErr_CheckSignals`, e " +"se isso definir o indicador de erro, deixa-o definido como tal. A função " +"retorna sempre ``NULL``, de forma que uma função que envolve uma chamada de " +"sistema pode retornar ``return PyErr_SetFromErrno(type);`` quando a chamada " +"de sistema retornar um erro." #: ../../c-api/exceptions.rst:199 msgid "" @@ -295,6 +336,10 @@ msgid "" "*type* as a third parameter. In the case of :exc:`OSError` exception, this " "is used to define the :attr:`!filename` attribute of the exception instance." msgstr "" +"Similar à :c:func:`PyErr_SetFromErrno`, com o comportamento adicional de " +"que, se *filenameObject* não é ``NULL``, ele é passado para o construtor de " +"*type* como um terceiro parâmetro. No caso da exceção :exc:`OSError`, isso é " +"usado para definir o atributo :attr:`!filename` da instância da exceção." #: ../../c-api/exceptions.rst:208 msgid "" @@ -302,6 +347,9 @@ msgid "" "second filename object, for raising errors when a function that takes two " "filenames fails." msgstr "" +"Similar à :c:func:`PyErr_SetFromErrnoWithFilenameObject`, mas recebe um " +"segundo objeto filename, para levantar erros quando uma função que recebe " +"dois nomes de arquivos falha." #: ../../c-api/exceptions.rst:217 msgid "" @@ -309,6 +357,9 @@ msgid "" "is given as a C string. *filename* is decoded from the :term:`filesystem " "encoding and error handler`." msgstr "" +"Similar à :c:func:`PyErr_SetFromErrnoWithFilenameObject`, mas o nome do " +"arquivo é fornecido como uma string C. *filename* é decodificado do :term:" +"`filesystem encoding and error handler`." #: ../../c-api/exceptions.rst:224 msgid "" @@ -323,18 +374,30 @@ msgid "" "``PyErr_SetObject(PyExc_OSError, object)``. This function always returns " "``NULL``." msgstr "" +"Essa é uma função conveniente para levantar :exc:`OSError`. Se chamada com " +"*ierr* de ``0``, o código de erro retornado por uma chamada para :c:func:`!" +"GetLastError` é usado instantaneamente. Ela chama a função Win32 :c:func:`!" +"FormatMessage` para retornar a descrição Windows do código de erro dado por " +"*ierr* ou :c:func:`!GetLastError`, e então constrói um objeto :exc:`OSError` " +"com o atributo :attr:`~OSError.winerror` definido para o código de erro, o " +"atributo :attr:`~OSError.strerror` definido para a mensagem de erro " +"correspondente (lida de :c:func:`!FormatMessage`), e então chama " +"``PyErr_SetObject(PyExc_OSError, object)``. Essa função sempre retorna " +"``NULL``." #: ../../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 "" "Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter " "specifying the exception type to be raised." msgstr "" +"Semelhante a :c:func:`PyErr_SetFromWindowsErr`, com um parâmetro adicional " +"que especifica o tipo de exceção a ser levantada." #: ../../c-api/exceptions.rst:247 msgid "" @@ -344,6 +407,11 @@ msgid "" "`OSError` as a third parameter to be used to define the :attr:`!filename` " "attribute of the exception instance." msgstr "" +"Semelhante a :c:func:`PyErr_SetFromWindowsErr`, com o comportamento " +"adicional de que, se *filename* não for ``NULL``, ele é decodificado a " +"partir da codificação do sistema de arquivos (:func:`os.fsdecode`) e passado " +"para o construtor de :exc:`OSError` como um terceiro parâmetro a ser usado " +"para definir o atributo :attr:`!filename` da instância da exceção." #: ../../c-api/exceptions.rst:258 msgid "" @@ -352,6 +420,10 @@ msgid "" "of :exc:`OSError` as a third parameter to be used to define the :attr:`!" "filename` attribute of the exception instance." msgstr "" +"Semelhante a :c:func:`PyErr_SetExcFromWindowsErr`, com o comportamento " +"adicional de que, se *filename* não for ``NULL``, ele é passado para o " +"construtor de :exc:`OSError` como um terceiro parâmetro a ser usado para " +"definir o atributo :attr:`!filename` da instância da exceção." #: ../../c-api/exceptions.rst:268 msgid "" @@ -376,6 +448,10 @@ msgid "" "be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name`` and " "``path`` attributes." msgstr "" +"Essa é uma função conveniente para levantar :exc:`ImportError`. *msg* será " +"definido como a string da mensagem de exceção. *name* e *path*, ambos os " +"quais podem ser ``NULL``, serão definidos como, respectivamente, os " +"atributos ``name`` e ``path`` de :exc:`ImportError`." #: ../../c-api/exceptions.rst:296 msgid "" @@ -392,18 +468,27 @@ msgid "" "attributes, which make the exception printing subsystem think the exception " "is a :exc:`SyntaxError`." msgstr "" +"Define informações de arquivo, linha e deslocamento para a atual exceção. Se " +"a exceção não é :exc:`SyntaxError`, define atributos adicionais, os quais " +"fazem o subsistema de impressão de exceções pensar que trata-se de um :exc:" +"`SyntaxError`." #: ../../c-api/exceptions.rst:314 msgid "" "Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string " "decoded from the :term:`filesystem encoding and error handler`." msgstr "" +"Como :c:func:`PyErr_SyntaxLocationObject`, mas *filename* é uma bytestring " +"descodificada a partir do :term:`tratador de erros e codificação do sistema " +"de arquivos`." #: ../../c-api/exceptions.rst:322 msgid "" "Like :c:func:`PyErr_SyntaxLocationEx`, but the *col_offset* parameter is " "omitted." msgstr "" +"Como :c:func:`PyErr_SyntaxLocationEx`, mas o parâmetro *col_offset* é " +"omitido." #: ../../c-api/exceptions.rst:328 msgid "" @@ -412,12 +497,44 @@ msgid "" "function) was invoked with an illegal argument. It is mostly for internal " "use." msgstr "" +"Essa é uma abreviação de ``PyErr_SetString(PyExc_SystemError, message)``, " +"onde *message* indica que uma operação interna (por exemplo, uma função API " +"C/Python) foi invocada com um argumento ilegal. Ela é principalmente para " +"uso interno." + +#: ../../c-api/exceptions.rst:336 +msgid "" +"Get the source line in *filename* at line *lineno*. *filename* should be a " +"Python :class:`str` object." +msgstr "" +"Obtém a linha de código-fonte em *filename* na linha *lineno*. *filename* " +"deve ser um objeto :class:`str` Python." -#: ../../c-api/exceptions.rst:335 +#: ../../c-api/exceptions.rst:339 +msgid "" +"On success, this function returns a Python string object with the found " +"line. On failure, this function returns ``NULL`` without an exception set." +msgstr "" +"Em caso de sucesso, esta função retorna um objeto string do Python com a " +"linha encontrada. Em caso de falha, esta função retorna ``NULL`` sem definir " +"uma exceção." + +#: ../../c-api/exceptions.rst:345 +msgid "" +"Similar to :c:func:`PyErr_ProgramTextObject`, but *filename* is a :c:expr:" +"`const char *`, which is decoded with the :term:`filesystem encoding and " +"error handler`, instead of a Python object reference." +msgstr "" +"Semelhante a :c:func:`PyErr_ProgramTextObject`, mas *filename* é um :c:expr:" +"`const char *`, que é decodificado com :term:`tratador de erros e " +"codificação do sistema de arquivos`, em vez de uma referência de objeto " +"Python." + +#: ../../c-api/exceptions.rst:352 msgid "Issuing warnings" -msgstr "Emitindo advertências" +msgstr "Emitindo avisos" -#: ../../c-api/exceptions.rst:337 +#: ../../c-api/exceptions.rst:354 msgid "" "Use these functions to issue warnings from C code. They mirror similar " "functions exported by the Python :mod:`warnings` module. They normally " @@ -432,8 +549,21 @@ msgid "" "exception handling (for example, :c:func:`Py_DECREF` owned references and " "return an error value)." msgstr "" - -#: ../../c-api/exceptions.rst:352 +"Use essas funções para emitir avisos a partir de código C. Elas espelham " +"funções semelhantes exportadas pelo módulo :mod:`warnings` do Python. " +"Normalmente, elas exibem uma mensagem de aviso em *sys.stderr*; no entanto, " +"também é possível que o usuário tenha especificado que os avisos devem ser " +"transformados em erros, e nesse caso, uma exceção será lançada. Também é " +"possível que as funções levantem uma exceção devido a um problema com o " +"mecanismo de avisos. O valor de retorno é ``0`` se nenhuma exceção for " +"lançada, ou ``-1`` se uma exceção for lançada. (Não é possível determinar se " +"uma mensagem de aviso é realmente impressa, nem qual é o motivo da exceção; " +"isso é intencional.) Se uma exceção for levantada, a função que chamou a " +"função deve realizar seu tratamento de exceções normal (por exemplo, liberar " +"as referências pertencentes a :c:func:`Py_DECREF` e retornar um valor de " +"erro)." + +#: ../../c-api/exceptions.rst:369 msgid "" "Issue a warning message. The *category* argument is a warning category (see " "below) or ``NULL``; the *message* argument is a UTF-8 encoded string. " @@ -442,8 +572,14 @@ msgid "" "stack frame. A *stack_level* of 1 is the function calling :c:func:" "`PyErr_WarnEx`, 2 is the function above that, and so forth." msgstr "" +"Emite uma mensagem de aviso. O argumento *category* é uma categoria de aviso " +"(veja abaixo) ou ``NULL``; o argumento *message* é uma string codificada em " +"UTF-8. *stack_level* é um número positivo que indica o número de quadros da " +"pilha; o aviso será emitido a partir da linha de código atualmente em " +"execução nesse quadro da pilha. Um *stack_level* de 1 é a função que chama :" +"c:func:`PyErr_WarnEx`, 2 é a função acima dessa e assim por diante." -#: ../../c-api/exceptions.rst:359 +#: ../../c-api/exceptions.rst:376 msgid "" "Warning categories must be subclasses of :c:data:`PyExc_Warning`; :c:data:" "`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`; the default " @@ -451,48 +587,71 @@ msgid "" "warning categories are available as global variables whose names are " "enumerated at :ref:`standardwarningcategories`." msgstr "" +"As categorias de aviso devem ser subclasses de :c:data:`PyExc_Warning`; :c:" +"data:`PyExc_Warning` é uma subclasse de :c:data:`PyExc_Exception`; a " +"categoria de aviso padrão é :c:data:`PyExc_RuntimeWarning`. As categorias de " +"aviso padrão do Python estão disponíveis como variáveis globais cujos nomes " +"estão enumerados em :ref:`standardwarningcategories`." -#: ../../c-api/exceptions.rst:365 +#: ../../c-api/exceptions.rst:382 msgid "" "For information about warning control, see the documentation for the :mod:" "`warnings` module and the :option:`-W` option in the command line " "documentation. There is no C API for warning control." msgstr "" +"Para obter informações sobre o controle de avisos, consulte a documentação " +"do módulo :mod:`warnings` e a opção :option:`-W` na documentação da linha de " +"comando. Não existe uma API C para o controle de avisos." -#: ../../c-api/exceptions.rst:372 +#: ../../c-api/exceptions.rst:389 msgid "" "Issue a warning message with explicit control over all warning attributes. " "This is a straightforward wrapper around the Python function :func:`warnings." "warn_explicit`; see there for more information. The *module* and *registry* " "arguments may be set to ``NULL`` to get the default effect described there." msgstr "" +"Emite uma mensagem de aviso com controle explícito sobre todos os atributos " +"de aviso. Trata-se de um invólucro simples em torno da função Python :func:" +"`warnings.warn_explicit`; consulte-a para obter mais informações. Os " +"argumentos *module* e *registry* podem ser definidos como ``NULL`` para " +"obter o efeito padrão descrito nessa função." -#: ../../c-api/exceptions.rst:383 +#: ../../c-api/exceptions.rst:400 msgid "" "Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and " "*module* are UTF-8 encoded strings, and *filename* is decoded from the :term:" "`filesystem encoding and error handler`." msgstr "" +"Semelhante a :c:func:`PyErr_WarnExplicitObject`, exceto que *message* e " +"*module* são strings codificadas em UTF-8 e *filename* é decodificado a " +"partir do :term:`tratador de erros e codificação do sistema de arquivos`." -#: ../../c-api/exceptions.rst:390 +#: ../../c-api/exceptions.rst:407 msgid "" "Function similar to :c:func:`PyErr_WarnEx`, but use :c:func:" "`PyUnicode_FromFormat` to format the warning message. *format* is an ASCII-" "encoded string." msgstr "" -#: ../../c-api/exceptions.rst:399 +#: ../../c-api/exceptions.rst:416 +msgid "" +"Similar to :c:func:`PyErr_WarnExplicit`, but uses :c:func:" +"`PyUnicode_FromFormat` to format the warning message. *format* is an ASCII-" +"encoded string." +msgstr "" + +#: ../../c-api/exceptions.rst:425 msgid "" "Function similar to :c:func:`PyErr_WarnFormat`, but *category* is :exc:" "`ResourceWarning` and it passes *source* to :class:`!warnings." "WarningMessage`." msgstr "" -#: ../../c-api/exceptions.rst:406 +#: ../../c-api/exceptions.rst:432 msgid "Querying the error indicator" msgstr "Consultando o indicador de erro" -#: ../../c-api/exceptions.rst:410 +#: ../../c-api/exceptions.rst:436 msgid "" "Test whether the error indicator is set. If set, return the exception " "*type* (the first argument to the last call to one of the ``PyErr_Set*`` " @@ -501,11 +660,11 @@ msgid "" "`Py_DECREF` it." msgstr "" -#: ../../c-api/exceptions.rst:416 +#: ../../c-api/exceptions.rst:442 msgid "The caller must hold the GIL." msgstr "" -#: ../../c-api/exceptions.rst:420 +#: ../../c-api/exceptions.rst:446 msgid "" "Do not compare the return value to a specific exception; use :c:func:" "`PyErr_ExceptionMatches` instead, shown below. (The comparison could easily " @@ -513,14 +672,14 @@ msgid "" "of a class exception, or it may be a subclass of the expected exception.)" msgstr "" -#: ../../c-api/exceptions.rst:428 +#: ../../c-api/exceptions.rst:454 msgid "" "Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This " "should only be called when an exception is actually set; a memory access " "violation will occur if no exception has been raised." msgstr "" -#: ../../c-api/exceptions.rst:435 +#: ../../c-api/exceptions.rst:461 msgid "" "Return true if the *given* exception matches the exception type in *exc*. " "If *exc* is a class object, this also returns true when *given* is an " @@ -528,43 +687,54 @@ msgid "" "tuple (and recursively in subtuples) are searched for a match." msgstr "" -#: ../../c-api/exceptions.rst:443 +#: ../../c-api/exceptions.rst:469 msgid "" "Return the exception currently being raised, clearing the error indicator at " "the same time. Return ``NULL`` if the error indicator is not set." msgstr "" -#: ../../c-api/exceptions.rst:446 +#: ../../c-api/exceptions.rst:472 msgid "" "This function is used by code that needs to catch exceptions, or code that " "needs to save and restore the error indicator temporarily." msgstr "" -#: ../../c-api/exceptions.rst:449 ../../c-api/exceptions.rst:493 +#: ../../c-api/exceptions.rst:475 ../../c-api/exceptions.rst:519 msgid "For example::" msgstr "Por exemplo::" -#: ../../c-api/exceptions.rst:459 +#: ../../c-api/exceptions.rst:477 +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:485 msgid "" ":c:func:`PyErr_GetHandledException`, to save the exception currently being " "handled." msgstr "" -#: ../../c-api/exceptions.rst:467 +#: ../../c-api/exceptions.rst:493 msgid "" "Set *exc* as the exception currently being raised, clearing the existing " "exception if one is set." msgstr "" -#: ../../c-api/exceptions.rst:472 +#: ../../c-api/exceptions.rst:498 msgid "This call steals a reference to *exc*, which must be a valid exception." msgstr "" -#: ../../c-api/exceptions.rst:481 +#: ../../c-api/exceptions.rst:507 msgid "Use :c:func:`PyErr_GetRaisedException` instead." -msgstr "" +msgstr "Use :c:func:`PyErr_GetRaisedException` em vez disso." -#: ../../c-api/exceptions.rst:483 +#: ../../c-api/exceptions.rst:509 msgid "" "Retrieve the error indicator into three variables whose addresses are " "passed. If the error indicator is not set, set all three variables to " @@ -573,17 +743,37 @@ msgid "" "the type object is not." msgstr "" -#: ../../c-api/exceptions.rst:490 +#: ../../c-api/exceptions.rst:516 msgid "" "This function is normally only used by legacy code that needs to catch " "exceptions or save and restore the error indicator temporarily." msgstr "" -#: ../../c-api/exceptions.rst:509 -msgid "Use :c:func:`PyErr_SetRaisedException` instead." +#: ../../c-api/exceptions.rst:521 +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 "" +"{\n" +"PyObject *type, *value, *traceback;\n" +"PyErr_Fetch(&type, &value, &traceback);\n" +"\n" +"/* ... código que pode reproduzir outros erros ... */\n" +"\n" +"PyErr_Restore(type, value, traceback);\n" +"}" + +#: ../../c-api/exceptions.rst:535 +msgid "Use :c:func:`PyErr_SetRaisedException` instead." +msgstr "Use :c:func:`PyErr_SetRaisedException` em vez disso." -#: ../../c-api/exceptions.rst:511 +#: ../../c-api/exceptions.rst:537 msgid "" "Set the error indicator from the three objects, *type*, *value*, and " "*traceback*, clearing the existing exception if one is set. If the objects " @@ -596,20 +786,22 @@ msgid "" "don't use this function. I warned you.)" msgstr "" -#: ../../c-api/exceptions.rst:525 +#: ../../c-api/exceptions.rst:551 msgid "" "This function is normally only used by legacy code that needs to save and " "restore the error indicator temporarily. Use :c:func:`PyErr_Fetch` to save " "the current error indicator." msgstr "" -#: ../../c-api/exceptions.rst:534 +#: ../../c-api/exceptions.rst:560 msgid "" "Use :c:func:`PyErr_GetRaisedException` instead, to avoid any possible de-" "normalization." msgstr "" +"Use :c:func:`PyErr_GetRaisedException` em vez disso, para evitar qualquer " +"possível desnormalização." -#: ../../c-api/exceptions.rst:537 +#: ../../c-api/exceptions.rst:563 msgid "" "Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` " "below can be \"unnormalized\", meaning that ``*exc`` is a class object but " @@ -619,14 +811,24 @@ msgid "" "improve performance." msgstr "" -#: ../../c-api/exceptions.rst:545 +#: ../../c-api/exceptions.rst:571 msgid "" "This function *does not* implicitly set the :attr:`~BaseException." "__traceback__` attribute on the exception value. If setting the traceback " "appropriately is desired, the following additional snippet is needed::" msgstr "" -#: ../../c-api/exceptions.rst:557 +#: ../../c-api/exceptions.rst:576 +msgid "" +"if (tb != NULL) {\n" +" PyException_SetTraceback(val, tb);\n" +"}" +msgstr "" +"if (tb != NULL) {\n" +"PyException_SetTraceback(val, tb);\n" +"}" + +#: ../../c-api/exceptions.rst:583 msgid "" "Retrieve the active exception instance, as would be returned by :func:`sys." "exception`. This refers to an exception that was *already caught*, not to an " @@ -634,7 +836,7 @@ msgid "" "or ``NULL``. Does not modify the interpreter's exception state." msgstr "" -#: ../../c-api/exceptions.rst:564 +#: ../../c-api/exceptions.rst:590 msgid "" "This function is not normally used by code that wants to handle exceptions. " "Rather, it can be used when code needs to save and restore the exception " @@ -642,14 +844,14 @@ msgid "" "clear the exception state." msgstr "" -#: ../../c-api/exceptions.rst:573 +#: ../../c-api/exceptions.rst:599 msgid "" "Set the active exception, as known from ``sys.exception()``. This refers to " "an exception that was *already caught*, not to an exception that was freshly " "raised. To clear the exception state, pass ``NULL``." msgstr "" -#: ../../c-api/exceptions.rst:580 +#: ../../c-api/exceptions.rst:606 msgid "" "This function is not normally used by code that wants to handle exceptions. " "Rather, it can be used when code needs to save and restore the exception " @@ -657,7 +859,7 @@ msgid "" "exception state." msgstr "" -#: ../../c-api/exceptions.rst:589 +#: ../../c-api/exceptions.rst:615 msgid "" "Retrieve the old-style representation of the exception info, as known from :" "func:`sys.exc_info`. This refers to an exception that was *already caught*, " @@ -667,7 +869,7 @@ msgid "" "using :c:func:`PyErr_GetHandledException`." msgstr "" -#: ../../c-api/exceptions.rst:598 +#: ../../c-api/exceptions.rst:624 msgid "" "This function is not normally used by code that wants to handle exceptions. " "Rather, it can be used when code needs to save and restore the exception " @@ -675,7 +877,7 @@ msgid "" "exception state." msgstr "" -#: ../../c-api/exceptions.rst:608 +#: ../../c-api/exceptions.rst:634 msgid "" "Set the exception info, as known from ``sys.exc_info()``. This refers to an " "exception that was *already caught*, not to an exception that was freshly " @@ -685,7 +887,7 @@ msgid "" "`PyErr_SetHandledException`." msgstr "" -#: ../../c-api/exceptions.rst:617 +#: ../../c-api/exceptions.rst:643 msgid "" "This function is not normally used by code that wants to handle exceptions. " "Rather, it can be used when code needs to save and restore the exception " @@ -693,22 +895,22 @@ msgid "" "state." msgstr "" -#: ../../c-api/exceptions.rst:624 +#: ../../c-api/exceptions.rst:650 msgid "" "The ``type`` and ``traceback`` arguments are no longer used and can be NULL. " "The interpreter now derives them from the exception instance (the ``value`` " "argument). The function still steals references of all three arguments." msgstr "" -#: ../../c-api/exceptions.rst:632 +#: ../../c-api/exceptions.rst:658 msgid "Signal Handling" msgstr "Tratamento de sinal" -#: ../../c-api/exceptions.rst:642 +#: ../../c-api/exceptions.rst:668 msgid "This function interacts with Python's signal handling." msgstr "Essa função interage com o manipulador de sinais do Python." -#: ../../c-api/exceptions.rst:644 +#: ../../c-api/exceptions.rst:670 msgid "" "If the function is called from the main thread and under the main Python " "interpreter, it checks whether a signal has been sent to the processes and " @@ -716,7 +918,7 @@ msgid "" "module is supported, this can invoke a signal handler written in Python." msgstr "" -#: ../../c-api/exceptions.rst:649 +#: ../../c-api/exceptions.rst:675 msgid "" "The function attempts to handle all pending signals, and then returns ``0``. " "However, if a Python signal handler raises an exception, the error indicator " @@ -725,44 +927,46 @@ msgid "" "`PyErr_CheckSignals()` invocation)." msgstr "" -#: ../../c-api/exceptions.rst:655 +#: ../../c-api/exceptions.rst:681 msgid "" "If the function is called from a non-main thread, or under a non-main Python " "interpreter, it does nothing and returns ``0``." msgstr "" -#: ../../c-api/exceptions.rst:658 +#: ../../c-api/exceptions.rst:684 msgid "" "This function can be called by long-running C code that wants to be " "interruptible by user requests (such as by pressing Ctrl-C)." msgstr "" -#: ../../c-api/exceptions.rst:662 +#: ../../c-api/exceptions.rst:688 msgid "" "The default Python signal handler for :c:macro:`!SIGINT` raises the :exc:" "`KeyboardInterrupt` exception." msgstr "" -#: ../../c-api/exceptions.rst:673 +#: ../../c-api/exceptions.rst:699 msgid "" "Simulate the effect of a :c:macro:`!SIGINT` signal arriving. This is " "equivalent to ``PyErr_SetInterruptEx(SIGINT)``." msgstr "" +"Simula o efeito de um sinal :c:macro:`!SIGINT` chegando. Isto é equivalente " +"a ``PyErr_SetInterruptEx(SIGINT)``." -#: ../../c-api/exceptions.rst:677 ../../c-api/exceptions.rst:704 +#: ../../c-api/exceptions.rst:703 ../../c-api/exceptions.rst:730 msgid "" "This function is async-signal-safe. It can be called without the :term:" "`GIL` and from a C signal handler." msgstr "" -#: ../../c-api/exceptions.rst:687 +#: ../../c-api/exceptions.rst:713 msgid "" "Simulate the effect of a signal arriving. The next time :c:func:" "`PyErr_CheckSignals` is called, the Python signal handler for the given " "signal number will be called." msgstr "" -#: ../../c-api/exceptions.rst:691 +#: ../../c-api/exceptions.rst:717 msgid "" "This function can be called by C code that sets up its own signal handling " "and wants Python signal handlers to be invoked as expected when an " @@ -770,27 +974,29 @@ msgid "" "interrupt an operation)." msgstr "" -#: ../../c-api/exceptions.rst:696 +#: ../../c-api/exceptions.rst:722 msgid "" "If the given signal isn't handled by Python (it was set to :py:const:`signal." "SIG_DFL` or :py:const:`signal.SIG_IGN`), it will be ignored." msgstr "" +"Se o sinal fornecido não for tratado pelo Python (foi definido como :py:" +"const:`signal.SIG_DFL` ou :py:const:`signal.SIG_IGN`), ele será ignorado." -#: ../../c-api/exceptions.rst:699 +#: ../../c-api/exceptions.rst:725 msgid "" "If *signum* is outside of the allowed range of signal numbers, ``-1`` is " "returned. Otherwise, ``0`` is returned. The error indicator is never " "changed by this function." msgstr "" -#: ../../c-api/exceptions.rst:712 +#: ../../c-api/exceptions.rst:738 msgid "" "This utility function specifies a file descriptor to which the signal number " "is written as a single byte whenever a signal is received. *fd* must be non-" "blocking. It returns the previous such file descriptor." msgstr "" -#: ../../c-api/exceptions.rst:716 +#: ../../c-api/exceptions.rst:742 msgid "" "The value ``-1`` disables the feature; this is the initial state. This is " "equivalent to :func:`signal.set_wakeup_fd` in Python, but without any error " @@ -802,15 +1008,15 @@ msgstr "" "verificação de erro. *fd* deve ser um descritor de arquivo válido. A função " "só deve ser chamada a partir da thread principal." -#: ../../c-api/exceptions.rst:721 +#: ../../c-api/exceptions.rst:747 msgid "On Windows, the function now also supports socket handles." msgstr "No Windows, a função agora também suporta manipuladores de socket." -#: ../../c-api/exceptions.rst:726 +#: ../../c-api/exceptions.rst:752 msgid "Exception Classes" msgstr "Classes de exceção" -#: ../../c-api/exceptions.rst:730 +#: ../../c-api/exceptions.rst:756 msgid "" "This utility function creates and returns a new exception class. The *name* " "argument must be the name of the new exception, a C string of the form " @@ -819,35 +1025,55 @@ msgid "" "(accessible in C as :c:data:`PyExc_Exception`)." msgstr "" -#: ../../c-api/exceptions.rst:736 +#: ../../c-api/exceptions.rst:762 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." msgstr "" -#: ../../c-api/exceptions.rst:745 +#: ../../c-api/exceptions.rst:771 msgid "" "Same as :c:func:`PyErr_NewException`, except that the new exception class " "can easily be given a docstring: If *doc* is non-``NULL``, it will be used " "as the docstring for the exception class." msgstr "" -#: ../../c-api/exceptions.rst:753 +#: ../../c-api/exceptions.rst:780 +msgid "" +"Return non-zero if *ob* is an exception class, zero otherwise. This function " +"always succeeds." +msgstr "" + +#: ../../c-api/exceptions.rst:785 +msgid "Return :c:member:`~PyTypeObject.tp_name` of the exception class *ob*." +msgstr "Retorna :c:member:`~PyTypeObject.tp_name` da classe de exceção *ob*." + +#: ../../c-api/exceptions.rst:789 msgid "Exception Objects" msgstr "Objeto Exceção" -#: ../../c-api/exceptions.rst:757 +#: ../../c-api/exceptions.rst:793 +msgid "" +"Return true if *op* is an instance of :class:`BaseException`, false " +"otherwise. This function always succeeds." +msgstr "" + +#: ../../c-api/exceptions.rst:799 +msgid "Equivalent to :c:func:`Py_TYPE(op) `." +msgstr "" + +#: ../../c-api/exceptions.rst:804 msgid "" "Return the traceback associated with the exception as a new reference, as " "accessible from Python through the :attr:`~BaseException.__traceback__` " "attribute. If there is no traceback associated, this returns ``NULL``." msgstr "" -#: ../../c-api/exceptions.rst:765 +#: ../../c-api/exceptions.rst:812 msgid "" "Set the traceback associated with the exception to *tb*. Use ``Py_None`` to " "clear it." @@ -855,7 +1081,7 @@ msgstr "" "Defina o retorno traceback (situação da pilha de execução) associado à " "exceção como *tb*. Use ``Py_None`` para limpá-lo." -#: ../../c-api/exceptions.rst:771 +#: ../../c-api/exceptions.rst:818 msgid "" "Return the context (another exception instance during whose handling *ex* " "was raised) associated with the exception as a new reference, as accessible " @@ -863,14 +1089,14 @@ msgid "" "there is no context associated, this returns ``NULL``." msgstr "" -#: ../../c-api/exceptions.rst:779 +#: ../../c-api/exceptions.rst:826 msgid "" "Set the context associated with the exception to *ctx*. Use ``NULL`` to " "clear it. There is no type check to make sure that *ctx* is an exception " "instance. This steals a reference to *ctx*." msgstr "" -#: ../../c-api/exceptions.rst:786 +#: ../../c-api/exceptions.rst:833 msgid "" "Return the cause (either an exception instance, or ``None``, set by " "``raise ... from ...``) associated with the exception as a new reference, as " @@ -878,28 +1104,28 @@ msgid "" "attribute." msgstr "" -#: ../../c-api/exceptions.rst:794 +#: ../../c-api/exceptions.rst:841 msgid "" "Set the cause associated with the exception to *cause*. Use ``NULL`` to " "clear it. There is no type check to make sure that *cause* is either an " "exception instance or ``None``. This steals a reference to *cause*." msgstr "" -#: ../../c-api/exceptions.rst:798 +#: ../../c-api/exceptions.rst:845 msgid "" "The :attr:`~BaseException.__suppress_context__` attribute is implicitly set " "to ``True`` by this function." msgstr "" -#: ../../c-api/exceptions.rst:804 +#: ../../c-api/exceptions.rst:851 msgid "Return :attr:`~BaseException.args` of exception *ex*." -msgstr "" +msgstr "Retorna :attr:`~BaseException.args` da exceção *ex*." -#: ../../c-api/exceptions.rst:809 +#: ../../c-api/exceptions.rst:856 msgid "Set :attr:`~BaseException.args` of exception *ex* to *args*." msgstr "" -#: ../../c-api/exceptions.rst:813 +#: ../../c-api/exceptions.rst:860 msgid "" "Implement part of the interpreter's implementation of :keyword:`!except*`. " "*orig* is the original exception that was caught, and *excs* is the list of " @@ -911,33 +1137,33 @@ msgid "" "if there is nothing to reraise." msgstr "" -#: ../../c-api/exceptions.rst:827 +#: ../../c-api/exceptions.rst:874 msgid "Unicode Exception Objects" msgstr "Objetos de exceção Unicode" -#: ../../c-api/exceptions.rst:829 +#: ../../c-api/exceptions.rst:876 msgid "" "The following functions are used to create and modify Unicode exceptions " "from C." msgstr "" "As seguintes funções são usadas para criar e modificar exceções Unicode de C." -#: ../../c-api/exceptions.rst:833 +#: ../../c-api/exceptions.rst:880 msgid "" "Create a :class:`UnicodeDecodeError` object with the attributes *encoding*, " "*object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are " "UTF-8 encoded strings." msgstr "" -#: ../../c-api/exceptions.rst:840 +#: ../../c-api/exceptions.rst:887 msgid "Return the *encoding* attribute of the given exception object." msgstr "Retorna o atributo * encoding* dado no objeto da exceção." -#: ../../c-api/exceptions.rst:846 +#: ../../c-api/exceptions.rst:893 msgid "Return the *object* attribute of the given exception object." msgstr "Retorna o atributo *object* dado no objeto da exceção." -#: ../../c-api/exceptions.rst:852 +#: ../../c-api/exceptions.rst:899 msgid "" "Get the *start* attribute of the given exception object and place it into " "*\\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` " @@ -947,7 +1173,7 @@ msgstr "" "*start* não deve ser ``NULL``. Retorna ``0`` se não der erro, ``-1`` caso dê " "erro." -#: ../../c-api/exceptions.rst:860 +#: ../../c-api/exceptions.rst:907 msgid "" "Set the *start* attribute of the given exception object to *start*. Return " "``0`` on success, ``-1`` on failure." @@ -955,7 +1181,7 @@ msgstr "" "Define o atributo *start* dado no objeto de exceção *start*. Em caso de " "sucesso, retorna ``0``, em caso de falha, retorna ``-1``." -#: ../../c-api/exceptions.rst:867 +#: ../../c-api/exceptions.rst:914 msgid "" "Get the *end* attribute of the given exception object and place it into " "*\\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on " @@ -965,27 +1191,27 @@ msgstr "" "*end* não deve ser ``NULL``. Em caso de sucesso, retorna ``0``, em caso de " "falha, retorna ``-1``." -#: ../../c-api/exceptions.rst:875 +#: ../../c-api/exceptions.rst:922 msgid "" "Set the *end* attribute of the given exception object to *end*. Return " "``0`` on success, ``-1`` on failure." msgstr "" -#: ../../c-api/exceptions.rst:882 +#: ../../c-api/exceptions.rst:929 msgid "Return the *reason* attribute of the given exception object." msgstr "Retorna o atributo *reason* dado no objeto da exceção." -#: ../../c-api/exceptions.rst:888 +#: ../../c-api/exceptions.rst:935 msgid "" "Set the *reason* attribute of the given exception object to *reason*. " "Return ``0`` on success, ``-1`` on failure." msgstr "" -#: ../../c-api/exceptions.rst:895 +#: ../../c-api/exceptions.rst:942 msgid "Recursion Control" msgstr "Controle de recursão" -#: ../../c-api/exceptions.rst:897 +#: ../../c-api/exceptions.rst:944 msgid "" "These two functions provide a way to perform safe recursive calls at the C " "level, both in the core and in extension modules. They are needed if the " @@ -995,46 +1221,48 @@ msgid "" "recursion handling." msgstr "" -#: ../../c-api/exceptions.rst:906 +#: ../../c-api/exceptions.rst:953 msgid "Marks a point where a recursive C-level call is about to be performed." msgstr "" "Marca um ponto em que a chamada recursiva em nível C está prestes a ser " "executada." -#: ../../c-api/exceptions.rst:908 +#: ../../c-api/exceptions.rst:955 msgid "" "If :c:macro:`!USE_STACKCHECK` is defined, this function checks if the OS " "stack overflowed using :c:func:`PyOS_CheckStack`. If this is the case, it " "sets a :exc:`MemoryError` and returns a nonzero value." msgstr "" -#: ../../c-api/exceptions.rst:912 +#: ../../c-api/exceptions.rst:959 msgid "" "The function then checks if the recursion limit is reached. If this is the " "case, a :exc:`RecursionError` is set and a nonzero value is returned. " "Otherwise, zero is returned." msgstr "" -#: ../../c-api/exceptions.rst:916 +#: ../../c-api/exceptions.rst:963 msgid "" "*where* should be a UTF-8 encoded string such as ``\" in instance check\"`` " "to be concatenated to the :exc:`RecursionError` message caused by the " "recursion depth limit." msgstr "" -#: ../../c-api/exceptions.rst:920 ../../c-api/exceptions.rst:928 +#: ../../c-api/exceptions.rst:967 ../../c-api/exceptions.rst:975 msgid "" "This function is now also available in the :ref:`limited API `." msgstr "" +"Esta função agora também está disponível na :ref:`API limitada `." -#: ../../c-api/exceptions.rst:925 +#: ../../c-api/exceptions.rst:972 msgid "" "Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each " "*successful* invocation of :c:func:`Py_EnterRecursiveCall`." msgstr "" -#: ../../c-api/exceptions.rst:931 +#: ../../c-api/exceptions.rst:978 msgid "" "Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types " "requires special recursion handling. In addition to protecting the stack, :" @@ -1043,7 +1271,7 @@ msgid "" "Effectively, these are the C equivalent to :func:`reprlib.recursive_repr`." msgstr "" -#: ../../c-api/exceptions.rst:939 +#: ../../c-api/exceptions.rst:986 msgid "" "Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` " "implementation to detect cycles." @@ -1051,7 +1279,7 @@ msgstr "" "Chamado no início da implementação :c:member:`~PyTypeObject.tp_repr` para " "detectar ciclos." -#: ../../c-api/exceptions.rst:942 +#: ../../c-api/exceptions.rst:989 msgid "" "If the object has already been processed, the function returns a positive " "integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation " @@ -1059,7 +1287,7 @@ msgid "" "`dict` objects return ``{...}`` and :class:`list` objects return ``[...]``." msgstr "" -#: ../../c-api/exceptions.rst:948 +#: ../../c-api/exceptions.rst:995 msgid "" "The function will return a negative integer if the recursion limit is " "reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation " @@ -1069,7 +1297,7 @@ msgstr "" "Nesse caso a implementação :c:member:`~PyTypeObject.tp_repr` deverá, " "normalmente,. retornar ``NULL``." -#: ../../c-api/exceptions.rst:952 +#: ../../c-api/exceptions.rst:999 msgid "" "Otherwise, the function returns zero and the :c:member:`~PyTypeObject." "tp_repr` implementation can continue normally." @@ -1077,7 +1305,7 @@ msgstr "" "Caso contrário, a função retorna zero e a implementação :c:member:" "`~PyTypeObject.tp_repr` poderá continuar normalmente." -#: ../../c-api/exceptions.rst:957 +#: ../../c-api/exceptions.rst:1004 msgid "" "Ends a :c:func:`Py_ReprEnter`. Must be called once for each invocation of :" "c:func:`Py_ReprEnter` that returns zero." @@ -1085,463 +1313,280 @@ msgstr "" "Termina a :c:func:`Py_ReprEnter`. Deve ser chamado uma vez para cada chamada " "de :c:func:`Py_ReprEnter` que retorna zero." -#: ../../c-api/exceptions.rst:964 -msgid "Standard Exceptions" -msgstr "Exceções Padrão" +#: ../../c-api/exceptions.rst:1009 +msgid "" +"Get the recursion limit for the current interpreter. It can be set with :c:" +"func:`Py_SetRecursionLimit`. The recursion limit prevents the Python " +"interpreter stack from growing infinitely." +msgstr "" + +#: ../../c-api/exceptions.rst:1013 ../../c-api/exceptions.rst:1023 +msgid "This function cannot fail, and the caller must hold the :term:`GIL`." +msgstr "" + +#: ../../c-api/exceptions.rst:1017 +msgid ":py:func:`sys.getrecursionlimit`" +msgstr "" + +#: ../../c-api/exceptions.rst:1021 +msgid "Set the recursion limit for the current interpreter." +msgstr "" + +#: ../../c-api/exceptions.rst:1027 +msgid ":py:func:`sys.setrecursionlimit`" +msgstr "" + +#: ../../c-api/exceptions.rst:1032 +msgid "Exception and warning types" +msgstr "" -#: ../../c-api/exceptions.rst:966 +#: ../../c-api/exceptions.rst:1034 msgid "" -"All standard Python exceptions are available as global variables whose names " -"are ``PyExc_`` followed by the Python exception name. These have the type :" -"c:expr:`PyObject*`; they are all class objects. For completeness, here are " -"all the variables:" +"All standard Python exceptions and warning categories are available as " +"global variables whose names are ``PyExc_`` followed by the Python exception " +"name. These have the type :c:expr:`PyObject*`; they are all class objects." msgstr "" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1160 -#: ../../c-api/exceptions.rst:1205 -msgid "C Name" -msgstr "Nome C" +#: ../../c-api/exceptions.rst:1038 +msgid "For completeness, here are all the variables:" +msgstr "" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1205 -msgid "Python Name" -msgstr "Nome Python" +#: ../../c-api/exceptions.rst:1041 +msgid "Exception types" +msgstr "Tipos de exceção" -#: ../../c-api/exceptions.rst:1027 ../../c-api/exceptions.rst:1160 -#: ../../c-api/exceptions.rst:1205 -msgid "Notes" -msgstr "Notas" +#: ../../c-api/exceptions.rst:1048 ../../c-api/exceptions.rst:1194 +#: ../../c-api/exceptions.rst:1224 +msgid "C name" +msgstr "Nome C" -#: ../../c-api/exceptions.rst:1029 -msgid ":c:data:`PyExc_BaseException`" -msgstr ":c:data:`PyExc_BaseException`" +#: ../../c-api/exceptions.rst:1049 ../../c-api/exceptions.rst:1195 +#: ../../c-api/exceptions.rst:1225 +msgid "Python name" +msgstr "Nome Python" -#: ../../c-api/exceptions.rst:1029 +#: ../../c-api/exceptions.rst:1051 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 -msgid "[1]_" -msgstr "[1]_" - -#: ../../c-api/exceptions.rst:1031 -msgid ":c:data:`PyExc_Exception`" -msgstr ":c:data:`PyExc_Exception`" +#: ../../c-api/exceptions.rst:1053 +msgid ":exc:`BaseExceptionGroup`" +msgstr ":exc:`BaseExceptionGroup`" -#: ../../c-api/exceptions.rst:1031 +#: ../../c-api/exceptions.rst:1055 msgid ":exc:`Exception`" msgstr ":exc:`Exception`" -#: ../../c-api/exceptions.rst:1033 -msgid ":c:data:`PyExc_ArithmeticError`" -msgstr ":c:data:`PyExc_ArithmeticError`" - -#: ../../c-api/exceptions.rst:1033 +#: ../../c-api/exceptions.rst:1057 msgid ":exc:`ArithmeticError`" msgstr ":exc:`ArithmeticError`" -#: ../../c-api/exceptions.rst:1035 -msgid ":c:data:`PyExc_AssertionError`" -msgstr ":c:data:`PyExc_AssertionError`" - -#: ../../c-api/exceptions.rst:1035 +#: ../../c-api/exceptions.rst:1059 msgid ":exc:`AssertionError`" msgstr ":exc:`AssertionError`" -#: ../../c-api/exceptions.rst:1037 -msgid ":c:data:`PyExc_AttributeError`" -msgstr ":c:data:`PyExc_AttributeError`" - -#: ../../c-api/exceptions.rst:1037 +#: ../../c-api/exceptions.rst:1061 msgid ":exc:`AttributeError`" msgstr ":exc:`AttributeError`" -#: ../../c-api/exceptions.rst:1039 -msgid ":c:data:`PyExc_BlockingIOError`" -msgstr ":c:data:`PyExc_BlockingIOError`" - -#: ../../c-api/exceptions.rst:1039 +#: ../../c-api/exceptions.rst:1063 msgid ":exc:`BlockingIOError`" msgstr ":exc:`BlockingIOError`" -#: ../../c-api/exceptions.rst:1041 -msgid ":c:data:`PyExc_BrokenPipeError`" -msgstr ":c:data:`PyExc_BrokenPipeError`" - -#: ../../c-api/exceptions.rst:1041 +#: ../../c-api/exceptions.rst:1065 msgid ":exc:`BrokenPipeError`" msgstr ":exc:`BrokenPipeError`" -#: ../../c-api/exceptions.rst:1043 -msgid ":c:data:`PyExc_BufferError`" -msgstr ":c:data:`PyExc_BufferError`" - -#: ../../c-api/exceptions.rst:1043 +#: ../../c-api/exceptions.rst:1067 msgid ":exc:`BufferError`" msgstr ":exc:`BufferError`" -#: ../../c-api/exceptions.rst:1045 -msgid ":c:data:`PyExc_ChildProcessError`" -msgstr ":c:data:`PyExc_ChildProcessError`" - -#: ../../c-api/exceptions.rst:1045 +#: ../../c-api/exceptions.rst:1069 msgid ":exc:`ChildProcessError`" msgstr ":exc:`ChildProcessError`" -#: ../../c-api/exceptions.rst:1047 -msgid ":c:data:`PyExc_ConnectionAbortedError`" -msgstr ":c:data:`PyExc_ConnectionAbortedError`" - -#: ../../c-api/exceptions.rst:1047 +#: ../../c-api/exceptions.rst:1071 msgid ":exc:`ConnectionAbortedError`" msgstr ":exc:`ConnectionAbortedError`" -#: ../../c-api/exceptions.rst:1049 -msgid ":c:data:`PyExc_ConnectionError`" -msgstr ":c:data:`PyExc_ConnectionError`" - -#: ../../c-api/exceptions.rst:1049 +#: ../../c-api/exceptions.rst:1073 msgid ":exc:`ConnectionError`" msgstr ":exc:`ConnectionError`" -#: ../../c-api/exceptions.rst:1051 -msgid ":c:data:`PyExc_ConnectionRefusedError`" -msgstr ":c:data:`PyExc_ConnectionRefusedError`" - -#: ../../c-api/exceptions.rst:1051 +#: ../../c-api/exceptions.rst:1075 msgid ":exc:`ConnectionRefusedError`" msgstr ":exc:`ConnectionRefusedError`" -#: ../../c-api/exceptions.rst:1053 -msgid ":c:data:`PyExc_ConnectionResetError`" -msgstr ":c:data:`PyExc_ConnectionResetError`" - -#: ../../c-api/exceptions.rst:1053 +#: ../../c-api/exceptions.rst:1077 msgid ":exc:`ConnectionResetError`" msgstr ":exc:`ConnectionResetError`" -#: ../../c-api/exceptions.rst:1055 -msgid ":c:data:`PyExc_EOFError`" -msgstr ":c:data:`PyExc_EOFError`" - -#: ../../c-api/exceptions.rst:1055 +#: ../../c-api/exceptions.rst:1079 msgid ":exc:`EOFError`" msgstr ":exc:`EOFError`" -#: ../../c-api/exceptions.rst:1057 -msgid ":c:data:`PyExc_FileExistsError`" -msgstr ":c:data:`PyExc_FileExistsError`" - -#: ../../c-api/exceptions.rst:1057 +#: ../../c-api/exceptions.rst:1081 msgid ":exc:`FileExistsError`" msgstr ":exc:`FileExistsError`" -#: ../../c-api/exceptions.rst:1059 -msgid ":c:data:`PyExc_FileNotFoundError`" -msgstr ":c:data:`PyExc_FileNotFoundError`" - -#: ../../c-api/exceptions.rst:1059 +#: ../../c-api/exceptions.rst:1083 msgid ":exc:`FileNotFoundError`" msgstr ":exc:`FileNotFoundError`" -#: ../../c-api/exceptions.rst:1061 -msgid ":c:data:`PyExc_FloatingPointError`" -msgstr ":c:data:`PyExc_FloatingPointError`" - -#: ../../c-api/exceptions.rst:1061 +#: ../../c-api/exceptions.rst:1085 msgid ":exc:`FloatingPointError`" msgstr ":exc:`FloatingPointError`" -#: ../../c-api/exceptions.rst:1063 -msgid ":c:data:`PyExc_GeneratorExit`" -msgstr ":c:data:`PyExc_GeneratorExit`" - -#: ../../c-api/exceptions.rst:1063 +#: ../../c-api/exceptions.rst:1087 msgid ":exc:`GeneratorExit`" msgstr ":exc:`GeneratorExit`" -#: ../../c-api/exceptions.rst:1065 -msgid ":c:data:`PyExc_ImportError`" -msgstr ":c:data:`PyExc_ImportError`" - -#: ../../c-api/exceptions.rst:1065 +#: ../../c-api/exceptions.rst:1089 msgid ":exc:`ImportError`" msgstr ":exc:`ImportError`" -#: ../../c-api/exceptions.rst:1067 -msgid ":c:data:`PyExc_IndentationError`" -msgstr ":c:data:`PyExc_IndentationError`" - -#: ../../c-api/exceptions.rst:1067 +#: ../../c-api/exceptions.rst:1091 msgid ":exc:`IndentationError`" msgstr ":exc:`IndentationError`" -#: ../../c-api/exceptions.rst:1069 -msgid ":c:data:`PyExc_IndexError`" -msgstr ":c:data:`PyExc_IndexError`" - -#: ../../c-api/exceptions.rst:1069 +#: ../../c-api/exceptions.rst:1093 msgid ":exc:`IndexError`" msgstr ":exc:`IndexError`" -#: ../../c-api/exceptions.rst:1071 -msgid ":c:data:`PyExc_InterruptedError`" -msgstr ":c:data:`PyExc_InterruptedError`" - -#: ../../c-api/exceptions.rst:1071 +#: ../../c-api/exceptions.rst:1095 msgid ":exc:`InterruptedError`" msgstr ":exc:`InterruptedError`" -#: ../../c-api/exceptions.rst:1073 -msgid ":c:data:`PyExc_IsADirectoryError`" -msgstr ":c:data:`PyExc_IsADirectoryError`" - -#: ../../c-api/exceptions.rst:1073 +#: ../../c-api/exceptions.rst:1097 msgid ":exc:`IsADirectoryError`" msgstr ":exc:`IsADirectoryError`" -#: ../../c-api/exceptions.rst:1075 -msgid ":c:data:`PyExc_KeyError`" -msgstr ":c:data:`PyExc_KeyError`" - -#: ../../c-api/exceptions.rst:1075 +#: ../../c-api/exceptions.rst:1099 msgid ":exc:`KeyError`" msgstr ":exc:`KeyError`" -#: ../../c-api/exceptions.rst:1077 -msgid ":c:data:`PyExc_KeyboardInterrupt`" -msgstr ":c:data:`PyExc_KeyboardInterrupt`" - -#: ../../c-api/exceptions.rst:1077 +#: ../../c-api/exceptions.rst:1101 msgid ":exc:`KeyboardInterrupt`" msgstr ":exc:`KeyboardInterrupt`" -#: ../../c-api/exceptions.rst:1079 -msgid ":c:data:`PyExc_LookupError`" -msgstr ":c:data:`PyExc_LookupError`" - -#: ../../c-api/exceptions.rst:1079 +#: ../../c-api/exceptions.rst:1103 msgid ":exc:`LookupError`" msgstr ":exc:`LookupError`" -#: ../../c-api/exceptions.rst:1081 -msgid ":c:data:`PyExc_MemoryError`" -msgstr ":c:data:`PyExc_MemoryError`" - -#: ../../c-api/exceptions.rst:1081 +#: ../../c-api/exceptions.rst:1105 msgid ":exc:`MemoryError`" msgstr ":exc:`MemoryError`" -#: ../../c-api/exceptions.rst:1083 -msgid ":c:data:`PyExc_ModuleNotFoundError`" -msgstr ":c:data:`PyExc_ModuleNotFoundError`" - -#: ../../c-api/exceptions.rst:1083 +#: ../../c-api/exceptions.rst:1107 msgid ":exc:`ModuleNotFoundError`" msgstr ":exc:`ModuleNotFoundError`" -#: ../../c-api/exceptions.rst:1085 -msgid ":c:data:`PyExc_NameError`" -msgstr ":c:data:`PyExc_NameError`" - -#: ../../c-api/exceptions.rst:1085 +#: ../../c-api/exceptions.rst:1109 msgid ":exc:`NameError`" msgstr ":exc:`NameError`" -#: ../../c-api/exceptions.rst:1087 -msgid ":c:data:`PyExc_NotADirectoryError`" -msgstr ":c:data:`PyExc_NotADirectoryError`" - -#: ../../c-api/exceptions.rst:1087 +#: ../../c-api/exceptions.rst:1111 msgid ":exc:`NotADirectoryError`" msgstr ":exc:`NotADirectoryError`" -#: ../../c-api/exceptions.rst:1089 -msgid ":c:data:`PyExc_NotImplementedError`" -msgstr ":c:data:`PyExc_NotImplementedError`" - -#: ../../c-api/exceptions.rst:1089 +#: ../../c-api/exceptions.rst:1113 msgid ":exc:`NotImplementedError`" msgstr ":exc:`NotImplementedError`" -#: ../../c-api/exceptions.rst:1091 -msgid ":c:data:`PyExc_OSError`" -msgstr ":c:data:`PyExc_OSError`" - -#: ../../c-api/exceptions.rst:1091 +#: ../../c-api/exceptions.rst:1115 ../../c-api/exceptions.rst:1198 +#: ../../c-api/exceptions.rst:1201 ../../c-api/exceptions.rst:1204 msgid ":exc:`OSError`" msgstr ":exc:`OSError`" -#: ../../c-api/exceptions.rst:1093 -msgid ":c:data:`PyExc_OverflowError`" -msgstr ":c:data:`PyExc_OverflowError`" - -#: ../../c-api/exceptions.rst:1093 +#: ../../c-api/exceptions.rst:1117 msgid ":exc:`OverflowError`" msgstr ":exc:`OverflowError`" -#: ../../c-api/exceptions.rst:1095 -msgid ":c:data:`PyExc_PermissionError`" -msgstr ":c:data:`PyExc_PermissionError`" - -#: ../../c-api/exceptions.rst:1095 +#: ../../c-api/exceptions.rst:1119 msgid ":exc:`PermissionError`" msgstr ":exc:`PermissionError`" -#: ../../c-api/exceptions.rst:1097 -msgid ":c:data:`PyExc_ProcessLookupError`" -msgstr ":c:data:`PyExc_ProcessLookupError`" - -#: ../../c-api/exceptions.rst:1097 +#: ../../c-api/exceptions.rst:1121 msgid ":exc:`ProcessLookupError`" msgstr ":exc:`ProcessLookupError`" -#: ../../c-api/exceptions.rst:1099 -msgid ":c:data:`PyExc_RecursionError`" -msgstr ":c:data:`PyExc_RecursionError`" +#: ../../c-api/exceptions.rst:1123 +msgid ":exc:`PythonFinalizationError`" +msgstr ":exc:`PythonFinalizationError`" -#: ../../c-api/exceptions.rst:1099 +#: ../../c-api/exceptions.rst:1125 msgid ":exc:`RecursionError`" msgstr ":exc:`RecursionError`" -#: ../../c-api/exceptions.rst:1101 -msgid ":c:data:`PyExc_ReferenceError`" -msgstr ":c:data:`PyExc_ReferenceError`" - -#: ../../c-api/exceptions.rst:1101 +#: ../../c-api/exceptions.rst:1127 msgid ":exc:`ReferenceError`" msgstr ":exc:`ReferenceError`" -#: ../../c-api/exceptions.rst:1103 -msgid ":c:data:`PyExc_RuntimeError`" -msgstr ":c:data:`PyExc_RuntimeError`" - -#: ../../c-api/exceptions.rst:1103 +#: ../../c-api/exceptions.rst:1129 msgid ":exc:`RuntimeError`" msgstr ":exc:`RuntimeError`" -#: ../../c-api/exceptions.rst:1105 -msgid ":c:data:`PyExc_StopAsyncIteration`" -msgstr ":c:data:`PyExc_StopAsyncIteration`" - -#: ../../c-api/exceptions.rst:1105 +#: ../../c-api/exceptions.rst:1131 msgid ":exc:`StopAsyncIteration`" msgstr ":exc:`StopAsyncIteration`" -#: ../../c-api/exceptions.rst:1107 -msgid ":c:data:`PyExc_StopIteration`" -msgstr ":c:data:`PyExc_StopIteration`" - -#: ../../c-api/exceptions.rst:1107 +#: ../../c-api/exceptions.rst:1133 msgid ":exc:`StopIteration`" msgstr ":exc:`StopIteration`" -#: ../../c-api/exceptions.rst:1109 -msgid ":c:data:`PyExc_SyntaxError`" -msgstr ":c:data:`PyExc_SyntaxError`" - -#: ../../c-api/exceptions.rst:1109 +#: ../../c-api/exceptions.rst:1135 msgid ":exc:`SyntaxError`" msgstr ":exc:`SyntaxError`" -#: ../../c-api/exceptions.rst:1111 -msgid ":c:data:`PyExc_SystemError`" -msgstr ":c:data:`PyExc_SystemError`" - -#: ../../c-api/exceptions.rst:1111 +#: ../../c-api/exceptions.rst:1137 msgid ":exc:`SystemError`" msgstr ":exc:`SystemError`" -#: ../../c-api/exceptions.rst:1113 -msgid ":c:data:`PyExc_SystemExit`" -msgstr ":c:data:`PyExc_SystemExit`" - -#: ../../c-api/exceptions.rst:1113 +#: ../../c-api/exceptions.rst:1139 msgid ":exc:`SystemExit`" msgstr ":exc:`SystemExit`" -#: ../../c-api/exceptions.rst:1115 -msgid ":c:data:`PyExc_TabError`" -msgstr ":c:data:`PyExc_TabError`" - -#: ../../c-api/exceptions.rst:1115 +#: ../../c-api/exceptions.rst:1141 msgid ":exc:`TabError`" msgstr ":exc:`TabError`" -#: ../../c-api/exceptions.rst:1117 -msgid ":c:data:`PyExc_TimeoutError`" -msgstr ":c:data:`PyExc_TimeoutError`" - -#: ../../c-api/exceptions.rst:1117 +#: ../../c-api/exceptions.rst:1143 msgid ":exc:`TimeoutError`" msgstr ":exc:`TimeoutError`" -#: ../../c-api/exceptions.rst:1119 -msgid ":c:data:`PyExc_TypeError`" -msgstr ":c:data:`PyExc_TypeError`" - -#: ../../c-api/exceptions.rst:1119 +#: ../../c-api/exceptions.rst:1145 msgid ":exc:`TypeError`" msgstr ":exc:`TypeError`" -#: ../../c-api/exceptions.rst:1121 -msgid ":c:data:`PyExc_UnboundLocalError`" -msgstr ":c:data:`PyExc_UnboundLocalError`" - -#: ../../c-api/exceptions.rst:1121 +#: ../../c-api/exceptions.rst:1147 msgid ":exc:`UnboundLocalError`" msgstr ":exc:`UnboundLocalError`" -#: ../../c-api/exceptions.rst:1123 -msgid ":c:data:`PyExc_UnicodeDecodeError`" -msgstr ":c:data:`PyExc_UnicodeDecodeError`" - -#: ../../c-api/exceptions.rst:1123 +#: ../../c-api/exceptions.rst:1149 msgid ":exc:`UnicodeDecodeError`" msgstr ":exc:`UnicodeDecodeError`" -#: ../../c-api/exceptions.rst:1125 -msgid ":c:data:`PyExc_UnicodeEncodeError`" -msgstr ":c:data:`PyExc_UnicodeEncodeError`" - -#: ../../c-api/exceptions.rst:1125 +#: ../../c-api/exceptions.rst:1151 msgid ":exc:`UnicodeEncodeError`" msgstr ":exc:`UnicodeEncodeError`" -#: ../../c-api/exceptions.rst:1127 -msgid ":c:data:`PyExc_UnicodeError`" -msgstr ":c:data:`PyExc_UnicodeError`" - -#: ../../c-api/exceptions.rst:1127 +#: ../../c-api/exceptions.rst:1153 msgid ":exc:`UnicodeError`" msgstr ":exc:`UnicodeError`" -#: ../../c-api/exceptions.rst:1129 -msgid ":c:data:`PyExc_UnicodeTranslateError`" -msgstr ":c:data:`PyExc_UnicodeTranslateError`" - -#: ../../c-api/exceptions.rst:1129 +#: ../../c-api/exceptions.rst:1155 msgid ":exc:`UnicodeTranslateError`" msgstr ":exc:`UnicodeTranslateError`" -#: ../../c-api/exceptions.rst:1131 -msgid ":c:data:`PyExc_ValueError`" -msgstr ":c:data:`PyExc_ValueError`" - -#: ../../c-api/exceptions.rst:1131 +#: ../../c-api/exceptions.rst:1157 msgid ":exc:`ValueError`" msgstr ":exc:`ValueError`" -#: ../../c-api/exceptions.rst:1133 -msgid ":c:data:`PyExc_ZeroDivisionError`" -msgstr ":c:data:`PyExc_ZeroDivisionError`" - -#: ../../c-api/exceptions.rst:1133 +#: ../../c-api/exceptions.rst:1159 msgid ":exc:`ZeroDivisionError`" msgstr ":exc:`ZeroDivisionError`" -#: ../../c-api/exceptions.rst:1136 +#: ../../c-api/exceptions.rst:1161 msgid "" ":c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, :c:data:" "`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, :c:data:" @@ -1561,453 +1606,165 @@ 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:1171 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:1174 msgid ":c:data:`PyExc_ModuleNotFoundError`." msgstr ":c:data:`PyExc_ModuleNotFoundError`." -#: ../../c-api/exceptions.rst:1152 -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:1177 +msgid ":c:data:`PyExc_BaseExceptionGroup`." +msgstr ":c:data:`PyExc_BaseExceptionGroup`." -#: ../../c-api/exceptions.rst:1162 -msgid ":c:data:`!PyExc_EnvironmentError`" +#: ../../c-api/exceptions.rst:1182 +msgid "OSError aliases" msgstr "" -#: ../../c-api/exceptions.rst:1164 -msgid ":c:data:`!PyExc_IOError`" -msgstr "" - -#: ../../c-api/exceptions.rst:1166 -msgid ":c:data:`!PyExc_WindowsError`" +#: ../../c-api/exceptions.rst:1184 +msgid "The following are a compatibility aliases to :c:data:`PyExc_OSError`." msgstr "" -#: ../../c-api/exceptions.rst:1166 -msgid "[2]_" -msgstr "[2]_" - -#: ../../c-api/exceptions.rst:1169 +#: ../../c-api/exceptions.rst:1186 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:1196 +msgid "Notes" +msgstr "Notas" + +#: ../../c-api/exceptions.rst:1205 +msgid "[win]_" +msgstr "[win]_" + +#: ../../c-api/exceptions.rst:1207 msgid "Notes:" msgstr "Notas:" -#: ../../c-api/exceptions.rst:1175 -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:1210 msgid "" -"Only defined on Windows; protect code that uses this by testing that the " -"preprocessor macro ``MS_WINDOWS`` is defined." +":c:var:`!PyExc_WindowsError` is only defined on Windows; protect code that " +"uses this by testing that the preprocessor macro ``MS_WINDOWS`` is defined." 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 -msgid "Standard Warning Categories" -msgstr "Categorias de aviso padrão" -#: ../../c-api/exceptions.rst:1186 -msgid "" -"All standard Python warning categories are available as global variables " -"whose names are ``PyExc_`` followed by the Python exception name. These have " -"the type :c:expr:`PyObject*`; they are all class objects. For completeness, " -"here are all the variables:" +#: ../../c-api/exceptions.rst:1217 +msgid "Warning types" msgstr "" -#: ../../c-api/exceptions.rst:1207 -msgid ":c:data:`PyExc_Warning`" -msgstr ":c:data:`PyExc_Warning`" - -#: ../../c-api/exceptions.rst:1207 +#: ../../c-api/exceptions.rst:1227 msgid ":exc:`Warning`" msgstr ":exc:`Warning`" -#: ../../c-api/exceptions.rst:1207 -msgid "[3]_" -msgstr "[3]_" - -#: ../../c-api/exceptions.rst:1209 -msgid ":c:data:`PyExc_BytesWarning`" -msgstr ":c:data:`PyExc_BytesWarning`" - -#: ../../c-api/exceptions.rst:1209 +#: ../../c-api/exceptions.rst:1229 msgid ":exc:`BytesWarning`" msgstr ":exc:`BytesWarning`" -#: ../../c-api/exceptions.rst:1211 -msgid ":c:data:`PyExc_DeprecationWarning`" -msgstr ":c:data:`PyExc_DeprecationWarning`" - -#: ../../c-api/exceptions.rst:1211 +#: ../../c-api/exceptions.rst:1231 msgid ":exc:`DeprecationWarning`" msgstr ":exc:`DeprecationWarning`" -#: ../../c-api/exceptions.rst:1213 -msgid ":c:data:`PyExc_FutureWarning`" -msgstr ":c:data:`PyExc_FutureWarning`" +#: ../../c-api/exceptions.rst:1233 +msgid ":exc:`EncodingWarning`" +msgstr ":exc:`EncodingWarning`" -#: ../../c-api/exceptions.rst:1213 +#: ../../c-api/exceptions.rst:1235 msgid ":exc:`FutureWarning`" msgstr ":exc:`FutureWarning`" -#: ../../c-api/exceptions.rst:1215 -msgid ":c:data:`PyExc_ImportWarning`" -msgstr ":c:data:`PyExc_ImportWarning`" - -#: ../../c-api/exceptions.rst:1215 +#: ../../c-api/exceptions.rst:1237 msgid ":exc:`ImportWarning`" msgstr ":exc:`ImportWarning`" -#: ../../c-api/exceptions.rst:1217 -msgid ":c:data:`PyExc_PendingDeprecationWarning`" -msgstr ":c:data:`PyExc_PendingDeprecationWarning`" - -#: ../../c-api/exceptions.rst:1217 +#: ../../c-api/exceptions.rst:1239 msgid ":exc:`PendingDeprecationWarning`" msgstr ":exc:`PendingDeprecationWarning`" -#: ../../c-api/exceptions.rst:1219 -msgid ":c:data:`PyExc_ResourceWarning`" -msgstr ":c:data:`PyExc_ResourceWarning`" - -#: ../../c-api/exceptions.rst:1219 +#: ../../c-api/exceptions.rst:1241 msgid ":exc:`ResourceWarning`" msgstr ":exc:`ResourceWarning`" -#: ../../c-api/exceptions.rst:1221 -msgid ":c:data:`PyExc_RuntimeWarning`" -msgstr ":c:data:`PyExc_RuntimeWarning`" - -#: ../../c-api/exceptions.rst:1221 +#: ../../c-api/exceptions.rst:1243 msgid ":exc:`RuntimeWarning`" msgstr ":exc:`RuntimeWarning`" -#: ../../c-api/exceptions.rst:1223 -msgid ":c:data:`PyExc_SyntaxWarning`" -msgstr ":c:data:`PyExc_SyntaxWarning`" - -#: ../../c-api/exceptions.rst:1223 +#: ../../c-api/exceptions.rst:1245 msgid ":exc:`SyntaxWarning`" msgstr ":exc:`SyntaxWarning`" -#: ../../c-api/exceptions.rst:1225 -msgid ":c:data:`PyExc_UnicodeWarning`" -msgstr ":c:data:`PyExc_UnicodeWarning`" - -#: ../../c-api/exceptions.rst:1225 +#: ../../c-api/exceptions.rst:1247 msgid ":exc:`UnicodeWarning`" msgstr ":exc:`UnicodeWarning`" -#: ../../c-api/exceptions.rst:1227 -msgid ":c:data:`PyExc_UserWarning`" -msgstr ":c:data:`PyExc_UserWarning`" - -#: ../../c-api/exceptions.rst:1227 +#: ../../c-api/exceptions.rst:1249 msgid ":exc:`UserWarning`" msgstr ":exc:`UserWarning`" -#: ../../c-api/exceptions.rst:1230 +#: ../../c-api/exceptions.rst:1251 msgid ":c:data:`PyExc_ResourceWarning`." msgstr ":c:data:`PyExc_ResourceWarning`." -#: ../../c-api/exceptions.rst:1236 -msgid "This is a base class for other standard warning categories." -msgstr "Esta é uma classe base para outras categorias de aviso padrão." - -#: ../../c-api/exceptions.rst:183 -msgid "strerror (C function)" -msgstr "" - -#: ../../c-api/exceptions.rst:637 ../../c-api/exceptions.rst:668 -#: ../../c-api/exceptions.rst:683 -msgid "module" -msgstr "módulo" - -#: ../../c-api/exceptions.rst:637 ../../c-api/exceptions.rst:668 -#: ../../c-api/exceptions.rst:683 -msgid "signal" -msgstr "signal" - -#: ../../c-api/exceptions.rst:637 ../../c-api/exceptions.rst:668 -msgid "SIGINT (C macro)" -msgstr "" - -#: ../../c-api/exceptions.rst:637 ../../c-api/exceptions.rst:668 -#: ../../c-api/exceptions.rst:683 -msgid "KeyboardInterrupt (built-in exception)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_BaseException (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_Exception (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ArithmeticError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_AssertionError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_AttributeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_BlockingIOError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_BrokenPipeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_BufferError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ChildProcessError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ConnectionAbortedError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ConnectionError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ConnectionRefusedError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ConnectionResetError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_EOFError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_FileExistsError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_FileNotFoundError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_FloatingPointError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_GeneratorExit (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ImportError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_IndentationError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_IndexError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_InterruptedError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_IsADirectoryError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_KeyError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_KeyboardInterrupt (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_LookupError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_MemoryError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ModuleNotFoundError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_NameError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_NotADirectoryError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_NotImplementedError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_OSError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_OverflowError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_PermissionError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ProcessLookupError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_RecursionError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ReferenceError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_RuntimeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_StopAsyncIteration (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_StopIteration (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_SyntaxError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_SystemError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_SystemExit (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_TabError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_TimeoutError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_TypeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_UnboundLocalError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_UnicodeDecodeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_UnicodeEncodeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_UnicodeError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_UnicodeTranslateError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ValueError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:971 -msgid "PyExc_ZeroDivisionError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:1154 -msgid "PyExc_EnvironmentError (C var)" -msgstr "" - -#: ../../c-api/exceptions.rst:1154 -msgid "PyExc_IOError (C var)" -msgstr "" +#: ../../c-api/exceptions.rst:1254 +msgid ":c:data:`PyExc_EncodingWarning`." +msgstr ":c:data:`PyExc_EncodingWarning`." -#: ../../c-api/exceptions.rst:1154 -msgid "PyExc_WindowsError (C var)" +#: ../../c-api/exceptions.rst:1259 +msgid "Tracebacks" msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_Warning (C var)" +#: ../../c-api/exceptions.rst:1263 +msgid "" +"Type object for traceback objects. This is available as :class:`types." +"TracebackType` in the Python layer." msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_BytesWarning (C var)" +#: ../../c-api/exceptions.rst:1269 +msgid "" +"Return true if *op* is a traceback object, false otherwise. This function " +"does not account for subtypes." msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_DeprecationWarning (C var)" +#: ../../c-api/exceptions.rst:1275 +msgid "" +"Replace the :attr:`~BaseException.__traceback__` attribute on the current " +"exception with a new traceback prepending *f* to the existing chain." msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_FutureWarning (C var)" +#: ../../c-api/exceptions.rst:1278 +msgid "Calling this function without an exception set is undefined behavior." msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_ImportWarning (C var)" +#: ../../c-api/exceptions.rst:1280 ../../c-api/exceptions.rst:1288 +msgid "" +"This function returns ``0`` on success, and returns ``-1`` with an exception " +"set on failure." msgstr "" +"Esta função retorna ``0`` em caso de sucesso e retorna ``-1`` com uma " +"exceção definida em caso de falha." -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_PendingDeprecationWarning (C var)" +#: ../../c-api/exceptions.rst:1286 +msgid "Write the traceback *tb* into the file *f*." msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_ResourceWarning (C var)" +#: ../../c-api/exceptions.rst:183 +msgid "strerror (C function)" msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_RuntimeWarning (C var)" -msgstr "" +#: ../../c-api/exceptions.rst:663 ../../c-api/exceptions.rst:694 +#: ../../c-api/exceptions.rst:709 +msgid "module" +msgstr "módulo" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_SyntaxWarning (C var)" -msgstr "" +#: ../../c-api/exceptions.rst:663 ../../c-api/exceptions.rst:694 +#: ../../c-api/exceptions.rst:709 +msgid "signal" +msgstr "signal" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_UnicodeWarning (C var)" +#: ../../c-api/exceptions.rst:663 ../../c-api/exceptions.rst:694 +msgid "SIGINT (C macro)" msgstr "" -#: ../../c-api/exceptions.rst:1191 -msgid "PyExc_UserWarning (C var)" +#: ../../c-api/exceptions.rst:663 ../../c-api/exceptions.rst:694 +#: ../../c-api/exceptions.rst:709 +msgid "KeyboardInterrupt (built-in exception)" msgstr "" diff --git a/c-api/file.po b/c-api/file.po index 3120316c8..246e2523a 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 +# python-doc bot, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -176,7 +176,31 @@ msgstr "" "Levanta um :ref:`evento de auditoria` ``setopencodehook`` sem " "argumentos." -#: ../../c-api/file.rst:101 +#: ../../c-api/file.rst:98 +msgid "" +"Open *path* with the mode ``'rb'``. *path* must be a Python :class:`str` " +"object. The behavior of this function may be overridden by :c:func:" +"`PyFile_SetOpenCodeHook` to allow for some preprocessing of the text." +msgstr "" + +#: ../../c-api/file.rst:103 +msgid "This is analogous to :func:`io.open_code` in Python." +msgstr "" + +#: ../../c-api/file.rst:105 +msgid "" +"On success, this function returns a :term:`strong reference` to a Python " +"file object. On failure, this function returns ``NULL`` with an exception " +"set." +msgstr "" + +#: ../../c-api/file.rst:114 +msgid "" +"Similar to :c:func:`PyFile_OpenCodeObject`, but *path* is a UTF-8 encoded :c:" +"expr:`const char*`." +msgstr "" + +#: ../../c-api/file.rst:124 msgid "" "Write object *obj* to file object *p*. The only supported flag for *flags* " "is :c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is " @@ -188,7 +212,7 @@ msgstr "" "objeto é escrito em vez de :func:`repr`. Retorna ``0`` em caso de sucesso ou " "``-1`` em caso de falha; a exceção apropriada será definida." -#: ../../c-api/file.rst:109 +#: ../../c-api/file.rst:132 msgid "" "Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on " "failure; the appropriate exception will be set." @@ -208,6 +232,6 @@ msgstr "arquivo" msgid "EOFError (built-in exception)" msgstr "EOFError (exceção embutida)" -#: ../../c-api/file.rst:99 +#: ../../c-api/file.rst:122 msgid "Py_PRINT_RAW (C macro)" msgstr "Py_PRINT_RAW (macro C)" diff --git a/c-api/float.po b/c-api/float.po index 8ec9d225f..f23446e4c 100644 --- a/c-api/float.po +++ b/c-api/float.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,11 +126,84 @@ msgstr "" "Retorna o ponto flutuante positivo mínimo normalizado *DBL_MIN* como :c:expr:" "`double` do C." -#: ../../c-api/float.rst:82 -msgid "Pack and Unpack functions" +#: ../../c-api/float.rst:83 +msgid "" +"This macro expands a to constant expression of type :c:expr:`double`, that " +"represents the positive infinity." +msgstr "" + +#: ../../c-api/float.rst:86 +msgid "" +"On most platforms, this is equivalent to the :c:macro:`!INFINITY` macro from " +"the C11 standard ```` header." +msgstr "" + +#: ../../c-api/float.rst:92 +msgid "" +"This macro expands a to constant expression of type :c:expr:`double`, that " +"represents a quiet not-a-number (qNaN) value." +msgstr "" + +#: ../../c-api/float.rst:95 +msgid "" +"On most platforms, this is equivalent to the :c:macro:`!NAN` macro from the " +"C11 standard ```` header." +msgstr "" + +#: ../../c-api/float.rst:101 +msgid "" +"The definition (accurate for a :c:expr:`double` type) of the :data:`math.e` " +"constant." +msgstr "" + +#: ../../c-api/float.rst:106 +msgid "High precision (long double) definition of :data:`~math.e` constant." msgstr "" -#: ../../c-api/float.rst:84 +#: ../../c-api/float.rst:111 +msgid "" +"The definition (accurate for a :c:expr:`double` type) of the :data:`math.pi` " +"constant." +msgstr "" + +#: ../../c-api/float.rst:116 +msgid "High precision (long double) definition of :data:`~math.pi` constant." +msgstr "" + +#: ../../c-api/float.rst:121 +msgid "" +"The definition (accurate for a :c:expr:`double` type) of the :data:`math." +"tau` constant." +msgstr "" + +#: ../../c-api/float.rst:128 +msgid "Return :data:`math.nan` from a function." +msgstr "" + +#: ../../c-api/float.rst:130 +msgid "" +"On most platforms, this is equivalent to ``return PyFloat_FromDouble(NAN)``." +msgstr "" + +#: ../../c-api/float.rst:135 +msgid "" +"Return :data:`math.inf` or :data:`-math.inf ` from a function, " +"depending on the sign of *sign*." +msgstr "" + +#: ../../c-api/float.rst:138 +msgid "On most platforms, this is equivalent to the following::" +msgstr "" + +#: ../../c-api/float.rst:140 +msgid "return PyFloat_FromDouble(copysign(INFINITY, sign));" +msgstr "" + +#: ../../c-api/float.rst:144 +msgid "Pack and Unpack functions" +msgstr "As funções Pack e Unpack" + +#: ../../c-api/float.rst:146 msgid "" "The pack and unpack functions provide an efficient platform-independent way " "to store floating-point values as byte strings. The Pack routines produce a " @@ -138,8 +211,14 @@ msgid "" "c:expr:`double` from such a bytes string. The suffix (2, 4 or 8) specifies " "the number of bytes in the bytes string." msgstr "" - -#: ../../c-api/float.rst:90 +"As funções de empacotamento e desempacotamento, pack e unpack " +"respectivamente, fornecem uma maneira eficiente e independente de plataforma " +"de armazenar valores de ponto flutuante como strings de bytes. As rotinas de " +"Pack produzem uma string de bytes a partir de um C :c:expr:`double`, e as " +"rotinas de Unpack produzem um C :c:expr:`double` a partir dessa string de " +"bytes. O sufixo (2, 4 ou 8) especifica o número de bytes na string de bytes." + +#: ../../c-api/float.rst:152 msgid "" "On platforms that appear to use IEEE 754 formats these functions work by " "copying bits. On other platforms, the 2-byte format is identical to the IEEE " @@ -150,20 +229,33 @@ msgid "" "attempting to unpack a bytes string containing an IEEE INF or NaN will raise " "an exception." msgstr "" - -#: ../../c-api/float.rst:99 +"Em plataformas que parecem usar o formato IEEE 754, essas funções funcionam " +"copiando bits. Em outras plataformas, o formato de 2 bytes é idêntico ao " +"formato de meia precisão binário 16 do IEEE 754, o formato de 4 bytes (32 " +"bits) é idêntico ao formato de precisão simples binário 32 do IEEE 754 e o " +"formato de 8 bytes ao formato de precisão dupla binário 64 do IEEE 754, " +"embora o empacotamento de INFs e NaNs (se tais recursos existirem na " +"plataforma) não seja tratado corretamente, e tentar desempacotar uma string " +"de bytes contendo um INF ou NaN do IEEE levantará uma exceção." + +#: ../../c-api/float.rst:161 msgid "" "On non-IEEE platforms with more precision, or larger dynamic range, than " "IEEE 754 supports, not all values can be packed; on non-IEEE platforms with " "less precision, or smaller dynamic range, not all values can be unpacked. " "What happens in such cases is partly accidental (alas)." msgstr "" +"Em plataformas que não aderem IEEE com maior precisão ou maior alcance " +"dinâmico do que o suportado pelo IEEE 754, nem todos os valores podem ser " +"empacotados; em plataformas que não aderem IEEE com menor precisão ou menor " +"alcance dinâmico, nem todos os valores podem ser desempacotados. O que " +"acontece nesses casos é em parte acidental (infelizmente)." -#: ../../c-api/float.rst:107 +#: ../../c-api/float.rst:169 msgid "Pack functions" -msgstr "" +msgstr "Funções Pack" -#: ../../c-api/float.rst:109 +#: ../../c-api/float.rst:171 msgid "" "The pack routines write 2, 4 or 8 bytes, starting at *p*. *le* is an :c:expr:" "`int` argument, non-zero if you want the bytes string in little-endian " @@ -172,42 +264,54 @@ msgid "" "`PY_BIG_ENDIAN` constant can be used to use the native endian: it is equal " "to ``1`` on big endian processor, or ``0`` on little endian processor." msgstr "" - -#: ../../c-api/float.rst:116 +"As rotinas de empacotamento gravam 2, 4 ou 8 bytes, começando em *p*. *le* é " +"um argumento :c:expr:`int`, diferente de zero se você quiser a sequência de " +"bytes no formato little-endian (expoente por último, em ``p+1``, ``p+3`` ou " +"``p+6`` ``p+7``), zero se você quiser o formato big-endian (expoente " +"primeiro, em *p*). A constante :c:macro:`PY_BIG_ENDIAN` pode ser usada para " +"usar o endian nativo: é igual a ``1`` em processadores big-endian ou ``0`` " +"em processadores little-endian." + +#: ../../c-api/float.rst:178 msgid "" "Return value: ``0`` if all is OK, ``-1`` if error (and an exception is set, " "most likely :exc:`OverflowError`)." msgstr "" +"Valor de retorno: ``0`` se tudo estiver OK, ``-1`` se houver erro (e uma " +"exceção for definida, provavelmente :exc:`OverflowError`)." -#: ../../c-api/float.rst:119 +#: ../../c-api/float.rst:181 msgid "There are two problems on non-IEEE platforms:" -msgstr "" +msgstr "Existem dois problemas em plataformas não IEEE:" -#: ../../c-api/float.rst:121 +#: ../../c-api/float.rst:183 msgid "What this does is undefined if *x* is a NaN or infinity." -msgstr "" +msgstr "O que isso faz é indefinido se *x* é um NaN ou infinito." -#: ../../c-api/float.rst:122 +#: ../../c-api/float.rst:184 msgid "``-0.0`` and ``+0.0`` produce the same bytes string." -msgstr "" +msgstr "``-0.0`` e ``+0.0`` produzem a mesma sequência de bytes." -#: ../../c-api/float.rst:126 +#: ../../c-api/float.rst:188 msgid "Pack a C double as the IEEE 754 binary16 half-precision format." msgstr "" +"Empacota um C duplo como o formato de meia precisão binário16 IEEE 754." -#: ../../c-api/float.rst:130 +#: ../../c-api/float.rst:192 msgid "Pack a C double as the IEEE 754 binary32 single precision format." msgstr "" +"Empacota um C duplo como o formato de precisão simples binário32 IEEE 754." -#: ../../c-api/float.rst:134 +#: ../../c-api/float.rst:196 msgid "Pack a C double as the IEEE 754 binary64 double precision format." msgstr "" +"Empacota um C duplo como o formato de precisão dupla binária 64 IEEE 754." -#: ../../c-api/float.rst:138 +#: ../../c-api/float.rst:200 msgid "Unpack functions" -msgstr "" +msgstr "Funções de Unpack" -#: ../../c-api/float.rst:140 +#: ../../c-api/float.rst:202 msgid "" "The unpack routines read 2, 4 or 8 bytes, starting at *p*. *le* is an :c:" "expr:`int` argument, non-zero if the bytes string is in little-endian format " @@ -216,31 +320,46 @@ msgid "" "be used to use the native endian: it is equal to ``1`` on big endian " "processor, or ``0`` on little endian processor." msgstr "" - -#: ../../c-api/float.rst:147 +"As rotinas de desempacotamento leem 2, 4 ou 8 bytes, começando em *p*. *le* " +"é um argumento :c:expr:`int`, diferente de zero se a sequência de bytes " +"estiver no formato little-endian (expoente por último, em ``p+1``, ``p+3`` " +"ou ``p+6`` e ``p+7``), zero se big-endian (expoente primeiro, em *p*). A " +"constante :c:macro:`PY_BIG_ENDIAN` pode ser usada para usar o endian nativo: " +"é igual a ``1`` em processadores big-endian ou ``0`` em processadores little-" +"endian." + +#: ../../c-api/float.rst:209 msgid "" "Return value: The unpacked double. On error, this is ``-1.0`` and :c:func:" "`PyErr_Occurred` is true (and an exception is set, most likely :exc:" "`OverflowError`)." msgstr "" +"Valor de retorno: O double descompactado. Em caso de erro, é ``-1.0`` e :c:" +"func:`PyErr_Occurred` é verdadeiro (e uma exceção é definida, provavelmente :" +"exc:`OverflowError`)." -#: ../../c-api/float.rst:151 +#: ../../c-api/float.rst:213 msgid "" "Note that on a non-IEEE platform this will refuse to unpack a bytes string " "that represents a NaN or infinity." msgstr "" +"Observe que em uma plataforma que não adere IEEE isso se recusará a " +"descompactar uma sequência de bytes que representa um NaN ou infinito." -#: ../../c-api/float.rst:156 +#: ../../c-api/float.rst:218 msgid "Unpack the IEEE 754 binary16 half-precision format as a C double." msgstr "" +"Descompacta o formato de meia precisão IEEE 754 binary16 como um double C." -#: ../../c-api/float.rst:160 +#: ../../c-api/float.rst:222 msgid "Unpack the IEEE 754 binary32 single precision format as a C double." msgstr "" +"Descompacta o formato IEEE 754 binary32 de precisão simples como um C double." -#: ../../c-api/float.rst:164 +#: ../../c-api/float.rst:226 msgid "Unpack the IEEE 754 binary64 double precision format as a C double." msgstr "" +"Descompacta o formato IEEE 754 binary64 de precisão dupla como um C double." #: ../../c-api/float.rst:8 msgid "object" diff --git a/c-api/frame.po b/c-api/frame.po index 60ca00632..21939bd83 100644 --- a/c-api/frame.po +++ b/c-api/frame.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,10 +72,17 @@ msgstr "" "h>``." #: ../../c-api/frame.rst:34 +msgid "" +"Create a new frame object. This function returns a :term:`strong reference` " +"to the new frame object on success, and returns ``NULL`` with an exception " +"set on failure." +msgstr "" + +#: ../../c-api/frame.rst:40 msgid "Return non-zero if *obj* is a frame object." msgstr "Retorna diferente de zero se *obj* é um objeto frame" -#: ../../c-api/frame.rst:38 +#: ../../c-api/frame.rst:44 msgid "" "Previously, this function was only available after including ````." @@ -84,39 +90,39 @@ msgstr "" "Anteriormente, esta função só estava disponível após incluir ````." -#: ../../c-api/frame.rst:43 +#: ../../c-api/frame.rst:49 msgid "Get the *frame* next outer frame." msgstr "Obtém o *frame* próximo ao quadro externo." -#: ../../c-api/frame.rst:45 +#: ../../c-api/frame.rst:51 msgid "" "Return a :term:`strong reference`, or ``NULL`` if *frame* has no outer frame." msgstr "" "Retorna uma :term:`referência forte` ou ``NULL`` se *frame* não tiver quadro " "externo." -#: ../../c-api/frame.rst:53 +#: ../../c-api/frame.rst:59 msgid "Get the *frame*'s :attr:`~frame.f_builtins` attribute." msgstr "" -#: ../../c-api/frame.rst:55 ../../c-api/frame.rst:86 +#: ../../c-api/frame.rst:61 ../../c-api/frame.rst:92 msgid "Return a :term:`strong reference`. The result cannot be ``NULL``." msgstr "" "Retorna uma :term:`referência forte`. O resultado não pode ser ``NULL``." -#: ../../c-api/frame.rst:62 +#: ../../c-api/frame.rst:68 msgid "Get the *frame* code." msgstr "Obtém o código de *frame*." -#: ../../c-api/frame.rst:64 ../../c-api/frame.rst:130 +#: ../../c-api/frame.rst:70 ../../c-api/frame.rst:136 msgid "Return a :term:`strong reference`." msgstr "Retorna uma :term:`referência forte`." -#: ../../c-api/frame.rst:66 +#: ../../c-api/frame.rst:72 msgid "The result (frame code) cannot be ``NULL``." msgstr "O resultado (código do frame) não pode ser ``NULL``." -#: ../../c-api/frame.rst:73 +#: ../../c-api/frame.rst:79 msgid "" "Get the generator, coroutine, or async generator that owns this frame, or " "``NULL`` if this frame is not owned by a generator. Does not raise an " @@ -126,50 +132,50 @@ msgstr "" "``NULL`` se o frame não pertence a um gerador. Não levanta exceção, mesmo " "que o valor retornado seja ``NULL``." -#: ../../c-api/frame.rst:77 +#: ../../c-api/frame.rst:83 msgid "Return a :term:`strong reference`, or ``NULL``." msgstr "Retorna uma :term:`referência forte`, ou ``NULL``." -#: ../../c-api/frame.rst:84 +#: ../../c-api/frame.rst:90 msgid "Get the *frame*'s :attr:`~frame.f_globals` attribute." msgstr "" -#: ../../c-api/frame.rst:93 +#: ../../c-api/frame.rst:99 msgid "Get the *frame*'s :attr:`~frame.f_lasti` attribute." msgstr "" -#: ../../c-api/frame.rst:95 +#: ../../c-api/frame.rst:101 msgid "Returns -1 if ``frame.f_lasti`` is ``None``." msgstr "Retorna -1 se ``frame.f_lasti`` é ``None``." -#: ../../c-api/frame.rst:102 +#: ../../c-api/frame.rst:108 msgid "Get the variable *name* of *frame*." msgstr "" -#: ../../c-api/frame.rst:104 +#: ../../c-api/frame.rst:110 msgid "Return a :term:`strong reference` to the variable value on success." msgstr "" -#: ../../c-api/frame.rst:105 +#: ../../c-api/frame.rst:111 msgid "" "Raise :exc:`NameError` and return ``NULL`` if the variable does not exist." msgstr "" -#: ../../c-api/frame.rst:106 +#: ../../c-api/frame.rst:112 msgid "Raise an exception and return ``NULL`` on error." msgstr "" -#: ../../c-api/frame.rst:108 +#: ../../c-api/frame.rst:114 msgid "*name* type must be a :class:`str`." msgstr "" -#: ../../c-api/frame.rst:115 +#: ../../c-api/frame.rst:121 msgid "" "Similar to :c:func:`PyFrame_GetVar`, but the variable name is a C string " "encoded in UTF-8." msgstr "" -#: ../../c-api/frame.rst:123 +#: ../../c-api/frame.rst:129 msgid "" "Get the *frame*'s :attr:`~frame.f_locals` attribute. If the frame refers to " "an :term:`optimized scope`, this returns a write-through proxy object that " @@ -178,35 +184,110 @@ msgid "" "directly (as described for :func:`locals`)." msgstr "" -#: ../../c-api/frame.rst:134 -msgid "As part of :pep:`667`, return a proxy object for optimized scopes." +#: ../../c-api/frame.rst:140 +msgid "" +"As part of :pep:`667`, return an instance of :c:var:" +"`PyFrameLocalsProxy_Type`." msgstr "" -#: ../../c-api/frame.rst:140 +#: ../../c-api/frame.rst:146 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:150 +msgid "Frame Locals Proxies" +msgstr "" + +#: ../../c-api/frame.rst:154 +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:160 +msgid "See :pep:`667` for more information." +msgstr "" + +#: ../../c-api/frame.rst:164 +msgid "The type of frame :func:`locals` proxy objects." +msgstr "" + +#: ../../c-api/frame.rst:168 +msgid "Return non-zero if *obj* is a frame :func:`locals` proxy." +msgstr "" + +#: ../../c-api/frame.rst:172 +msgid "Legacy Local Variable APIs" +msgstr "" + +#: ../../c-api/frame.rst:174 +msgid "" +"These APIs are :term:`soft deprecated`. As of Python 3.13, they do nothing. " +"They exist solely for backwards compatibility." +msgstr "" + +#: ../../c-api/frame.rst:180 ../../c-api/frame.rst:194 +#: ../../c-api/frame.rst:207 +msgid "This function is :term:`soft deprecated` and does nothing." +msgstr "" + +#: ../../c-api/frame.rst:182 +msgid "" +"Prior to Python 3.13, this function would copy the :attr:`~frame.f_locals` " +"attribute of *f* to the internal \"fast\" array of local variables, allowing " +"changes in frame objects to be visible to the interpreter. If *clear* was " +"true, this function would process variables that were unset in the locals " +"dictionary." +msgstr "" + +#: ../../c-api/frame.rst:188 ../../c-api/frame.rst:201 +#: ../../c-api/frame.rst:213 +msgid "This function now does nothing." +msgstr "Esta função agora não faz nada." + +#: ../../c-api/frame.rst:196 +msgid "" +"Prior to Python 3.13, this function would copy the internal \"fast\" array " +"of local variables (which is used by the interpreter) to the :attr:`~frame." +"f_locals` attribute of *f*, allowing changes in local variables to be " +"visible to frame objects." +msgstr "" + +#: ../../c-api/frame.rst:209 +msgid "" +"Prior to Python 3.13, this function was similar to :c:func:" +"`PyFrame_FastToLocals`, but would return ``0`` on success, and ``-1`` with " +"an exception set on failure." +msgstr "" + +#: ../../c-api/frame.rst:218 +msgid ":pep:`667`" +msgstr "" + +#: ../../c-api/frame.rst:222 msgid "Internal Frames" msgstr "" -#: ../../c-api/frame.rst:147 +#: ../../c-api/frame.rst:224 msgid "Unless using :pep:`523`, you will not need this." msgstr "" -#: ../../c-api/frame.rst:151 +#: ../../c-api/frame.rst:228 msgid "The interpreter's internal frame representation." msgstr "" -#: ../../c-api/frame.rst:157 +#: ../../c-api/frame.rst:234 msgid "Return a :term:`strong reference` to the code object for the frame." msgstr "" -#: ../../c-api/frame.rst:164 +#: ../../c-api/frame.rst:241 msgid "Return the byte offset into the last executed instruction." msgstr "" -#: ../../c-api/frame.rst:171 +#: ../../c-api/frame.rst:248 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..87d996cea 100644 --- a/c-api/function.po +++ b/c-api/function.po @@ -1,32 +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: -# Italo Penaforte , 2021 -# Rafael Fontenelle , 2023 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +43,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 +51,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 +61,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 +72,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 +85,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,53 +105,85 @@ 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 +#: ../../c-api/function.rst:86 ../../c-api/function.rst:125 +#: ../../c-api/function.rst:139 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:101 +msgid "" +"Return the keyword-only argument default values of the function object *op*. " +"This can be a dictionary of arguments or ``NULL``." +msgstr "" +"Retorna os valores-padrão de argumentos somente-nomeados do objeto função " +"*op*. Pode ser um dicionário de argumentos ou ``NULL``." + +#: ../../c-api/function.rst:107 +msgid "" +"Set the keyword-only argument default values of the function object *op*. " +"*defaults* must be a dictionary of keyword-only arguments or ``Py_None``." +msgstr "" +"Define os valores padrão dos argumentos somente-nomeados do objeto função " +"*op*. *defaults* deve ser um dicionário de argumentos somente-nomeados ou " +"``Py_None``." -#: ../../c-api/function.rst:100 +#: ../../c-api/function.rst:110 +msgid "" +"This function returns ``0`` on success, and returns ``-1`` with an exception " +"set on failure." +msgstr "" +"Esta função retorna ``0`` em caso de sucesso e retorna ``-1`` com uma " +"exceção definida em caso de falha." + +#: ../../c-api/function.rst:116 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 +#: ../../c-api/function.rst:122 msgid "" "Set the closure associated with the function object *op*. *closure* must be " "``Py_None`` or a tuple of cell objects." @@ -149,7 +191,7 @@ msgstr "" "Define o fechamento associado ao objeto função *op*. *closure* deve ser " "``Py_None`` ou uma tupla de objetos de célula." -#: ../../c-api/function.rst:114 +#: ../../c-api/function.rst:130 msgid "" "Return the annotations of the function object *op*. This can be a mutable " "dictionary or ``NULL``." @@ -157,7 +199,7 @@ msgstr "" "Retorna as anotações do objeto função *op*. Este pode ser um dicionário " "mutável ou ``NULL``." -#: ../../c-api/function.rst:120 +#: ../../c-api/function.rst:136 msgid "" "Set the annotations for the function object *op*. *annotations* must be a " "dictionary or ``Py_None``." @@ -165,52 +207,92 @@ msgstr "" "Define as anotações para o objeto função *op*. *annotations* deve ser um " "dicionário ou ``Py_None``." -#: ../../c-api/function.rst:128 +#: ../../c-api/function.rst:150 +msgid "" +"These functions are similar to their ``PyFunction_Get*`` counterparts, but " +"do not do type checking. Passing anything other than an instance of :c:data:" +"`PyFunction_Type` is undefined behavior." +msgstr "" +"Essas funções são semelhantes às suas contrapartes ``PyFunction_Get*``, mas " +"não realizam verificação de tipos. Passar qualquer coisa que não seja uma " +"instância de :c:data:`PyFunction_Type` é um comportamento indefinido." + +#: ../../c-api/function.rst:157 msgid "" "Register *callback* as a function watcher for the current interpreter. " "Return an ID which may be passed to :c:func:`PyFunction_ClearWatcher`. In " "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 +#: ../../c-api/function.rst:167 msgid "" "Clear watcher identified by *watcher_id* previously returned from :c:func:" "`PyFunction_AddWatcher` for the current interpreter. Return ``0`` on " "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``" -msgstr "" +#: ../../c-api/function.rst:177 +msgid "Enumeration of possible function watcher events:" +msgstr "Enumeração de possíveis eventos do observador de funções:" + +#: ../../c-api/function.rst:179 +msgid "``PyFunction_EVENT_CREATE``" +msgstr "``PyFunction_EVENT_CREATE``" + +#: ../../c-api/function.rst:180 +msgid "``PyFunction_EVENT_DESTROY``" +msgstr "``PyFunction_EVENT_DESTROY``" -#: ../../c-api/function.rst:160 +#: ../../c-api/function.rst:181 +msgid "``PyFunction_EVENT_MODIFY_CODE``" +msgstr "``PyFunction_EVENT_MODIFY_CODE``" + +#: ../../c-api/function.rst:182 +msgid "``PyFunction_EVENT_MODIFY_DEFAULTS``" +msgstr "``PyFunction_EVENT_MODIFY_DEFAULTS``" + +#: ../../c-api/function.rst:183 +msgid "``PyFunction_EVENT_MODIFY_KWDEFAULTS``" +msgstr "``PyFunction_EVENT_MODIFY_KWDEFAULTS``" + +#: ../../c-api/function.rst:190 msgid "Type of a function watcher callback function." -msgstr "" +msgstr "Tipo de uma função de retorno de sentinela de função." -#: ../../c-api/function.rst:162 +#: ../../c-api/function.rst:192 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:197 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:200 msgid "" "If *event* is ``PyFunction_EVENT_CREATE``, then the callback is invoked " -"after `func` has been fully initialized. Otherwise, the callback is invoked " +"after *func* has been fully initialized. Otherwise, the callback is invoked " "before the modification to *func* takes place, so the prior state of *func* " "can be inspected. The runtime is permitted to optimize away the creation of " "function objects when possible. In such cases no event will be emitted. " @@ -218,26 +300,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:209 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:214 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:218 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 +340,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..8b6838475 100644 --- a/c-api/gcsupport.po +++ b/c-api/gcsupport.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,8 +38,8 @@ msgid "" "explicit support for garbage collection." msgstr "" "O suporte do Python para detectar e coletar o lixo, que envolve referencias " -"circulares, requer suporte dos tipos de objetos que são \"contêiners\" para " -"outros objetos que também podem ser contêiners. Tipos que não armazenam " +"circulares, requer suporte dos tipos de objetos que são \"contêineres\" para " +"outros objetos que também podem ser contêineres. Tipos que não armazenam " "referências a outros tipos de objetos, ou que apenas armazenam referências a " "tipos atômicos (como números ou strings), não precisam fornecer nenhum " "suporte explicito para coleta de lixo." @@ -83,8 +82,8 @@ msgid "" "Once all the fields which may contain references to other containers are " "initialized, it must call :c:func:`PyObject_GC_Track`." msgstr "" -"Uma vez que todos os campos que podem conter referências a outros containers " -"foram inicializados, deve-se chamar :c:func:`PyObject_GC_Track`." +"Uma vez que todos os campos que podem conter referências a outros " +"contêineres foram inicializados, deve-se chamar :c:func:`PyObject_GC_Track`." #: ../../c-api/gcsupport.rst:34 msgid "" @@ -99,7 +98,7 @@ msgid "" "Before fields which refer to other containers are invalidated, :c:func:" "`PyObject_GC_UnTrack` must be called." msgstr "" -"Antes que os campos que fazer referência a outros containers sejam " +"Antes que os campos que fazer referência a outros contêineres sejam " "invalidados, :c:func:`PyObject_GC_UnTrack` deve ser chamado." #: ../../c-api/gcsupport.rst:40 @@ -279,9 +278,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 +386,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..75d5969ba 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..6abe478c9 100644 --- a/c-api/hash.po +++ b/c-api/hash.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-09 14:58+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,11 +38,62 @@ msgstr "" msgid "Hash value type: signed integer." msgstr "Tipo de valor do hash: inteiro com sinal." -#: ../../c-api/hash.rst:16 +#: ../../c-api/hash.rst:17 msgid "Hash value type: unsigned integer." msgstr "Tipo de valor do hash: inteiro sem sinal." -#: ../../c-api/hash.rst:22 +#: ../../c-api/hash.rst:24 +msgid "" +"A numerical value indicating the algorithm for hashing of :class:`str`, :" +"class:`bytes`, and :class:`memoryview`." +msgstr "" + +#: ../../c-api/hash.rst:27 +msgid "The algorithm name is exposed by :data:`sys.hash_info.algorithm`." +msgstr "" + +#: ../../c-api/hash.rst:36 +msgid "" +"Numerical values to compare to :c:macro:`Py_HASH_ALGORITHM` to determine " +"which algorithm is used for hashing. The hash algorithm can be configured " +"via the configure :option:`--with-hash-algorithm` option." +msgstr "" + +#: ../../c-api/hash.rst:40 +msgid "Add :c:macro:`!Py_HASH_FNV` and :c:macro:`!Py_HASH_SIPHASH24`." +msgstr "" + +#: ../../c-api/hash.rst:43 +msgid "Add :c:macro:`!Py_HASH_SIPHASH13`." +msgstr "" + +#: ../../c-api/hash.rst:49 +msgid "" +"Buffers of length in range ``[1, Py_HASH_CUTOFF)`` are hashed using DJBX33A " +"instead of the algorithm described by :c:macro:`Py_HASH_ALGORITHM`." +msgstr "" + +#: ../../c-api/hash.rst:52 +msgid "A :c:macro:`!Py_HASH_CUTOFF` of 0 disables the optimization." +msgstr "" + +#: ../../c-api/hash.rst:53 +msgid "" +":c:macro:`!Py_HASH_CUTOFF` must be non-negative and less or equal than 7." +msgstr "" + +#: ../../c-api/hash.rst:55 +msgid "" +"32-bit platforms should use a cutoff smaller than 64-bit platforms because " +"it is easier to create colliding strings. A cutoff of 7 on 64-bit platforms " +"and 5 on 32-bit platforms should provide a decent safety margin." +msgstr "" + +#: ../../c-api/hash.rst:59 +msgid "This corresponds to the :data:`sys.hash_info.cutoff` constant." +msgstr "" + +#: ../../c-api/hash.rst:66 msgid "" "The `Mersenne prime `_ ``P = " "2**n -1``, used for numeric hash scheme." @@ -50,47 +101,75 @@ msgstr "" "O `primo de Mersenne `_ ``P " "= 2**n -1``, usado para esquema de hash numérico." -#: ../../c-api/hash.rst:28 +#: ../../c-api/hash.rst:69 +msgid "This corresponds to the :data:`sys.hash_info.modulus` constant." +msgstr "" + +#: ../../c-api/hash.rst:76 msgid "The exponent ``n`` of ``P`` in :c:macro:`PyHASH_MODULUS`." msgstr "O expoente ``n`` de ``P`` em :c:macro:`PyHASH_MODULUS`." -#: ../../c-api/hash.rst:34 +#: ../../c-api/hash.rst:83 msgid "Prime multiplier used in string and various other hashes." msgstr "Multiplicador de primo usado em strings e vários outros hashes." -#: ../../c-api/hash.rst:40 +#: ../../c-api/hash.rst:90 msgid "The hash value returned for a positive infinity." msgstr "O valor de hash retornado para um infinito positivo." -#: ../../c-api/hash.rst:46 +#: ../../c-api/hash.rst:92 +msgid "This corresponds to the :data:`sys.hash_info.inf` constant." +msgstr "" + +#: ../../c-api/hash.rst:99 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." -#: ../../c-api/hash.rst:52 +#: ../../c-api/hash.rst:101 +msgid "This corresponds to the :data:`sys.hash_info.imag` constant." +msgstr "" + +#: ../../c-api/hash.rst:108 msgid "Hash function definition used by :c:func:`PyHash_GetFuncDef`." msgstr "Definição de função de hash usada por :c:func:`PyHash_GetFuncDef`." -#: ../../c-api/hash.rst:60 +#: ../../c-api/hash.rst:112 +msgid "Hash function." +msgstr "Função de hash." + +#: ../../c-api/hash.rst:116 msgid "Hash function name (UTF-8 encoded string)." msgstr "Nome de função hash (string codificada em UTF-8)." -#: ../../c-api/hash.rst:64 +#: ../../c-api/hash.rst:118 +msgid "This corresponds to the :data:`sys.hash_info.algorithm` constant." +msgstr "" + +#: ../../c-api/hash.rst:122 msgid "Internal size of the hash value in bits." msgstr "Tamanho interno do valor do hash em bits." -#: ../../c-api/hash.rst:68 +#: ../../c-api/hash.rst:124 +msgid "This corresponds to the :data:`sys.hash_info.hash_bits` constant." +msgstr "" + +#: ../../c-api/hash.rst:128 msgid "Size of seed input in bits." msgstr "Tamanho da entrada de seed em bits." -#: ../../c-api/hash.rst:75 +#: ../../c-api/hash.rst:130 +msgid "This corresponds to the :data:`sys.hash_info.seed_bits` constant." +msgstr "" + +#: ../../c-api/hash.rst:137 msgid "Get the hash function definition." msgstr "Obtém a definição de função de hash." -#: ../../c-api/hash.rst:78 +#: ../../c-api/hash.rst:140 msgid ":pep:`456` \"Secure and interchangeable hash algorithm\"." msgstr ":pep:`456` \"Algoritmo de hash seguro e intercambiável\"." -#: ../../c-api/hash.rst:85 +#: ../../c-api/hash.rst:147 msgid "" "Hash a pointer value: process the pointer value as an integer (cast it to " "``uintptr_t`` internally). The pointer is not dereferenced." @@ -99,11 +178,11 @@ msgstr "" "(converte-o para ``uintptr_t`` internamente). O ponteiro não é " "desreferenciado." -#: ../../c-api/hash.rst:88 +#: ../../c-api/hash.rst:150 msgid "The function cannot fail: it cannot return ``-1``." msgstr "A função não pode falhar: ela não pode retornar ``-1``." -#: ../../c-api/hash.rst:94 +#: ../../c-api/hash.rst:156 msgid "" "Generic hashing function that is meant to be put into a type object's " "``tp_hash`` slot. Its result only depends on the object's identity." @@ -111,6 +190,6 @@ msgstr "" "Função de hash genérica que deve ser colocada no slot ``tp_hash`` de um " "objeto de tipo. Seu resultado depende apenas da identidade do objeto." -#: ../../c-api/hash.rst:99 +#: ../../c-api/hash.rst:161 msgid "In CPython, it is equivalent to :c:func:`Py_HashPointer`." msgstr "No CPython, é equivalente a :c:func:`Py_HashPointer`." diff --git a/c-api/import.po b/c-api/import.po index 642f57785..21a0fdaf1 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..36e54cbec 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..3dc9bb2b5 100644 --- a/c-api/init.po +++ b/c-api/init.po @@ -1,50 +1,46 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-11 14:58+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +52,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 +246,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 +258,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 +278,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 +300,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 +308,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 +334,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 +352,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 +377,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 +385,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 +427,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 +435,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 +468,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 +494,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 +502,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 +536,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 +562,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 +584,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 +592,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 +610,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 +653,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 +676,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 +684,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 +699,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: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:379 +#: ../../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 +792,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 +822,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__` " @@ -692,10 +842,14 @@ msgid "" "extension modules may not be freed. Some extensions may not work properly " "if their initialization routine is called more than once; this can happen if " "an application calls :c:func:`Py_Initialize` and :c:func:`Py_FinalizeEx` " -"more than once." +"more than once. :c:func:`Py_FinalizeEx` must not be called recursively from " +"within itself. Therefore, it must not be called by any code that may be run " +"as part of the interpreter shutdown process, such as :py:mod:`atexit` " +"handlers, object finalizers, or any code that may be run while flushing the " +"stdout and stderr files." msgstr "" -#: ../../c-api/init.rst:429 +#: ../../c-api/init.rst:456 msgid "" "Raises an :ref:`auditing event ` ``cpython." "_PySys_ClearAuditHooks`` with no arguments." @@ -703,24 +857,188 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "_PySys_ClearAuditHooks`` sem argumentos." -#: ../../c-api/init.rst:435 +#: ../../c-api/init.rst:463 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:469 +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:478 +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:484 +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:488 +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:495 +msgid "" +"The return value is ``2`` if the argument list does not represent a valid " +"Python command line, and otherwise the same as :c:func:`Py_RunMain`." +msgstr "" + +#: ../../c-api/init.rst:498 +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:502 +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:510 +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:440 +#: ../../c-api/init.rst:523 +msgid "Executes the main module in a fully configured CPython runtime." +msgstr "" + +#: ../../c-api/init.rst:525 +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:531 +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), the exit status of an unhandled :exc:`SystemExit`, or ``1`` for " +"any other unhandled exception." +msgstr "" + +#: ../../c-api/init.rst:536 +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: ``0``, ``1``, or the " +"status of a :exc:`SystemExit`, as specified above." +msgstr "" + +#: ../../c-api/init.rst:544 +msgid "" +"This function always finalizes the Python interpreter before it returns." +msgstr "" + +#: ../../c-api/init.rst:546 +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:552 +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:556 +msgid "The :term:`GIL` must be held for *interp*." +msgstr "" + +#: ../../c-api/init.rst:561 msgid "Process-wide parameters" msgstr "" -#: ../../c-api/init.rst:450 +#: ../../c-api/init.rst:571 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:575 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 +1062,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:586 ../../c-api/init.rst:828 ../../c-api/init.rst:864 +#: ../../c-api/init.rst:890 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:594 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:598 ../../c-api/init.rst:620 ../../c-api/init.rst:666 +#: ../../c-api/init.rst:688 ../../c-api/init.rst:714 ../../c-api/init.rst:902 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:601 ../../c-api/init.rst:623 ../../c-api/init.rst:669 +#: ../../c-api/init.rst:691 ../../c-api/init.rst:719 ../../c-api/init.rst:905 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:604 ../../c-api/init.rst:694 msgid "Get :data:`sys.executable` instead." msgstr "" -#: ../../c-api/init.rst:489 +#: ../../c-api/init.rst:610 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 +1102,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:626 +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:633 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 +1122,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:644 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 +1135,7 @@ msgid "" "independent may be installed in :file:`/usr/local`." msgstr "" -#: ../../c-api/init.rst:527 +#: ../../c-api/init.rst:650 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 +1149,7 @@ msgid "" "independent from the Python version by which they were compiled!)." msgstr "" -#: ../../c-api/init.rst:538 +#: ../../c-api/init.rst:661 msgid "" "System administrators will know how to configure the :program:`mount` or :" "program:`automount` programs to share :file:`/usr/local` between platforms " @@ -837,11 +1157,13 @@ msgid "" "platform." msgstr "" -#: ../../c-api/init.rst:549 -msgid "Get :data:`sys.exec_prefix` instead." +#: ../../c-api/init.rst:672 +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:682 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 +1172,7 @@ msgid "" "available to Python code as ``sys.executable``." msgstr "" -#: ../../c-api/init.rst:580 +#: ../../c-api/init.rst:704 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 +1185,11 @@ msgid "" "for loading modules." msgstr "" -#: ../../c-api/init.rst:598 +#: ../../c-api/init.rst:722 msgid "Get :data:`sys.path` instead." msgstr "" -#: ../../c-api/init.rst:604 +#: ../../c-api/init.rst:728 msgid "" "Return the version of this Python interpreter. This is a string that looks " "something like ::" @@ -875,7 +1197,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:731 +msgid "\"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \\n[GCC 4.2.3]\"" +msgstr "" + +#: ../../c-api/init.rst:735 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 +1210,11 @@ msgid "" "version`." msgstr "" -#: ../../c-api/init.rst:616 +#: ../../c-api/init.rst:740 msgid "See also the :c:var:`Py_Version` constant." msgstr "" -#: ../../c-api/init.rst:623 +#: ../../c-api/init.rst:747 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 +1225,7 @@ msgid "" "available to Python code as ``sys.platform``." msgstr "" -#: ../../c-api/init.rst:634 +#: ../../c-api/init.rst:758 msgid "" "Return the official copyright string for the current Python version, for " "example" @@ -907,17 +1233,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:760 msgid "``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``" -msgstr "" +msgstr "``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``" -#: ../../c-api/init.rst:640 +#: ../../c-api/init.rst:764 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:770 msgid "" "Return an indication of the compiler used to build the current Python " "version, in square brackets, for example::" @@ -925,14 +1251,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:773 +msgid "\"[GCC 2.7.2.2]\"" +msgstr "" + +#: ../../c-api/init.rst:777 ../../c-api/init.rst:791 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:784 msgid "" "Return information about the sequence number and build date and time of the " "current Python interpreter instance, for example ::" @@ -940,7 +1270,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:787 +msgid "\"#67, Aug 1 1997, 22:34:28\"" +msgstr "" + +#: ../../c-api/init.rst:803 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 +1282,7 @@ msgid "" "config>`." msgstr "" -#: ../../c-api/init.rst:684 +#: ../../c-api/init.rst:808 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 +1293,7 @@ msgid "" "fatal condition is signalled using :c:func:`Py_FatalError`." msgstr "" -#: ../../c-api/init.rst:692 +#: ../../c-api/init.rst:816 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 +1303,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:820 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:823 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:831 ../../c-api/init.rst:867 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:835 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:840 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:844 +msgid "PyRun_SimpleString(\"import sys; sys.path.pop(0)\\n\");" +msgstr "" + +#: ../../c-api/init.rst:856 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:860 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:870 msgid "The *updatepath* value depends on :option:`-I`." msgstr "" -#: ../../c-api/init.rst:753 +#: ../../c-api/init.rst:877 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:881 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:885 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 +1381,24 @@ msgid "" "this storage." msgstr "" -#: ../../c-api/init.rst:774 +#: ../../c-api/init.rst:898 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:908 msgid "" "Get :c:member:`PyConfig.home` or :envvar:`PYTHONHOME` environment variable " "instead." msgstr "" -#: ../../c-api/init.rst:792 +#: ../../c-api/init.rst:916 msgid "Thread State and the Global Interpreter Lock" -msgstr "" +msgstr "Estado de thread e a trava global do interpretador" -#: ../../c-api/init.rst:799 +#: ../../c-api/init.rst:923 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 +1410,7 @@ msgid "" "once instead of twice." msgstr "" -#: ../../c-api/init.rst:809 +#: ../../c-api/init.rst:933 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 +1419,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:943 msgid "" "The Python interpreter keeps some thread-specific bookkeeping information " "inside a data structure called :c:type:`PyThreadState`. There's also one " @@ -1090,11 +1435,11 @@ msgid "" "retrieved using :c:func:`PyThreadState_Get`." msgstr "" -#: ../../c-api/init.rst:825 +#: ../../c-api/init.rst:949 msgid "Releasing the GIL from extension code" msgstr "" -#: ../../c-api/init.rst:827 +#: ../../c-api/init.rst:951 msgid "" "Most extension code manipulating the :term:`GIL` has the following simple " "structure::" @@ -1102,11 +1447,30 @@ 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:954 +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:960 msgid "This is so common that a pair of macros exists to simplify it::" +msgstr "Isso é tão comum que existe um par de macros para simplificá-lo::" + +#: ../../c-api/init.rst:962 +msgid "" +"Py_BEGIN_ALLOW_THREADS\n" +"... Do some blocking I/O operation ...\n" +"Py_END_ALLOW_THREADS" msgstr "" +"Py_BEGIN_ALLOW_THREADS\n" +"... Faça alguma operação de E/S com bloqueio...\n" +"Py_END_ALLOW_THREADS" -#: ../../c-api/init.rst:846 +#: ../../c-api/init.rst:970 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 +1479,25 @@ 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:974 msgid "The block above expands to the following code::" +msgstr "O bloco acima se expande para o seguinte código::" + +#: ../../c-api/init.rst:976 +msgid "" +"PyThreadState *_save;\n" +"\n" +"_save = PyEval_SaveThread();\n" +"... Do some blocking I/O operation ...\n" +"PyEval_RestoreThread(_save);" msgstr "" +"PyThreadState *_save;\n" +"\n" +"_save = PyEval_SaveThread();\n" +"... Faça alguma operação de E/S com bloqueio...\n" +"PyEval_RestoreThread(_save);" -#: ../../c-api/init.rst:862 +#: ../../c-api/init.rst:986 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 +1508,7 @@ msgid "" "state, the lock must be acquired before storing the thread state pointer." msgstr "" -#: ../../c-api/init.rst:871 +#: ../../c-api/init.rst:995 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 +1518,11 @@ msgid "" "compressing or hashing data." msgstr "" -#: ../../c-api/init.rst:882 +#: ../../c-api/init.rst:1006 msgid "Non-Python created threads" msgstr "" -#: ../../c-api/init.rst:884 +#: ../../c-api/init.rst:1008 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 +1532,7 @@ msgid "" "for them." msgstr "" -#: ../../c-api/init.rst:891 +#: ../../c-api/init.rst:1015 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 +1543,27 @@ msgid "" "finally free the thread state data structure." msgstr "" -#: ../../c-api/init.rst:899 +#: ../../c-api/init.rst:1023 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:1027 +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:1037 msgid "" "Note that the ``PyGILState_*`` functions assume there is only one global " "interpreter (created automatically by :c:func:`Py_Initialize`). Python " @@ -1181,11 +1572,11 @@ msgid "" "``PyGILState_*`` API is unsupported." msgstr "" -#: ../../c-api/init.rst:923 +#: ../../c-api/init.rst:1047 msgid "Cautions about fork()" msgstr "Cuidados com o uso de fork()" -#: ../../c-api/init.rst:925 +#: ../../c-api/init.rst:1049 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 +1585,7 @@ msgid "" "CPython's runtime." msgstr "" -#: ../../c-api/init.rst:931 +#: ../../c-api/init.rst:1055 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 +1602,7 @@ msgid "" "locks, but is not always able to." msgstr "" -#: ../../c-api/init.rst:946 +#: ../../c-api/init.rst:1070 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 +1615,50 @@ msgid "" "called immediately after." msgstr "" -#: ../../c-api/init.rst:959 +#: ../../c-api/init.rst:1084 +msgid "Cautions regarding runtime finalization" +msgstr "" + +#: ../../c-api/init.rst:1086 +msgid "" +"In the late stage of :term:`interpreter shutdown`, after attempting to wait " +"for non-daemon threads to exit (though this can be interrupted by :class:" +"`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime is " +"marked as *finalizing*: :c:func:`Py_IsFinalizing` and :func:`sys." +"is_finalizing` return true. At this point, only the *finalization thread* " +"that initiated finalization (typically the main thread) is allowed to " +"acquire the :term:`GIL`." +msgstr "" + +#: ../../c-api/init.rst:1094 +msgid "" +"If any thread, other than the finalization thread, attempts to acquire the " +"GIL during finalization, either explicitly via :c:func:`PyGILState_Ensure`, :" +"c:macro:`Py_END_ALLOW_THREADS`, :c:func:`PyEval_AcquireThread`, or :c:func:`!" +"PyEval_AcquireLock`, or implicitly when the interpreter attempts to " +"reacquire it after having yielded it, the thread enters **a permanently " +"blocked state** where it remains until the program exits. In most cases " +"this is harmless, but this can result in deadlock if a later stage of " +"finalization attempts to acquire a lock owned by the blocked thread, or " +"otherwise waits on the blocked thread." +msgstr "" + +#: ../../c-api/init.rst:1104 +msgid "" +"Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++ " +"finalizations further up the call stack when such threads were forcibly " +"exited here in CPython 3.13.7 and earlier. The CPython runtime GIL acquiring " +"C APIs have never had any error reporting or handling expectations at GIL " +"acquisition time that would've allowed for graceful exit from this " +"situation. Changing that would require new stable C APIs and rewriting the " +"majority of C code in the CPython ecosystem to use those with error handling." +msgstr "" + +#: ../../c-api/init.rst:1114 msgid "High-level API" msgstr "" -#: ../../c-api/init.rst:961 +#: ../../c-api/init.rst:1116 msgid "" "These are the most commonly used types and functions when writing C " "extension code, or when embedding the Python interpreter:" @@ -1236,7 +1666,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:1121 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 +1674,7 @@ msgid "" "in this structure." msgstr "" -#: ../../c-api/init.rst:971 +#: ../../c-api/init.rst:1126 msgid "" "Threads belonging to different interpreters initially share nothing, except " "process state like available memory, open file descriptors and such. The " @@ -1252,30 +1682,36 @@ msgid "" "which interpreter they belong." msgstr "" -#: ../../c-api/init.rst:979 +#: ../../c-api/init.rst:1133 +msgid "" +":pep:`684` introduced the possibility of a :ref:`per-interpreter GIL `. See :c:func:`Py_NewInterpreterFromConfig`." +msgstr "" + +#: ../../c-api/init.rst:1140 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:1145 msgid "This thread's interpreter state." msgstr "" -#: ../../c-api/init.rst:995 +#: ../../c-api/init.rst:1156 msgid "Deprecated function which does nothing." msgstr "Função descontinuada que não faz nada." -#: ../../c-api/init.rst:997 +#: ../../c-api/init.rst:1158 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:1160 msgid "The function now does nothing." msgstr "" -#: ../../c-api/init.rst:1002 +#: ../../c-api/init.rst:1163 msgid "" "This function is now called by :c:func:`Py_Initialize()`, so you don't have " "to call it yourself anymore." @@ -1283,13 +1719,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:1167 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:1177 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 +1733,7 @@ msgid "" "acquired it." msgstr "" -#: ../../c-api/init.rst:1024 +#: ../../c-api/init.rst:1185 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,54 +1741,79 @@ msgid "" "ensues." msgstr "" -#: ../../c-api/init.rst:1030 ../../c-api/init.rst:1089 -#: ../../c-api/init.rst:1371 +#: ../../c-api/init.rst:1191 ../../c-api/init.rst:1267 +#: ../../c-api/init.rst:1569 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 " -"use :c:func:`Py_IsFinalizing` or :func:`sys.is_finalizing` to check if the " -"interpreter is in process of being finalized before calling this function to " -"avoid unwanted termination." +"Calling this function from a thread when the runtime is finalizing will hang " +"the thread until the program exits, even if the thread was not created by " +"Python. Refer to :ref:`cautions-regarding-runtime-finalization` for more " +"details." msgstr "" -#: ../../c-api/init.rst:1038 +#: ../../c-api/init.rst:1196 ../../c-api/init.rst:1272 +#: ../../c-api/init.rst:1579 +msgid "" +"Hangs the current thread, rather than terminating it, if called while the " +"interpreter is finalizing." +msgstr "" + +#: ../../c-api/init.rst:1202 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:1206 msgid "See also :c:func:`PyThreadState_GetUnchecked`." msgstr "" -#: ../../c-api/init.rst:1047 +#: ../../c-api/init.rst:1211 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:1215 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:1222 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:1063 +#: ../../c-api/init.rst:1225 +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:1228 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:1233 +msgid "" +"The type of the value returned by :c:func:`PyGILState_Ensure` and passed to :" +"c:func:`PyGILState_Release`." +msgstr "" + +#: ../../c-api/init.rst:1238 +msgid "The GIL was already held when :c:func:`PyGILState_Ensure` was called." +msgstr "" + +#: ../../c-api/init.rst:1242 +msgid "The GIL was not held when :c:func:`PyGILState_Ensure` was called." +msgstr "" + +#: ../../c-api/init.rst:1246 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 +1835,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:1256 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 +1845,13 @@ msgid "" "func:`PyGILState_Release`." msgstr "" -#: ../../c-api/init.rst:1085 +#: ../../c-api/init.rst:1263 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:1278 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 +1859,13 @@ msgid "" "caller, hence the use of the GILState API)." msgstr "" -#: ../../c-api/init.rst:1102 +#: ../../c-api/init.rst:1283 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:1289 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 +1873,7 @@ msgid "" "made on the main thread. This is mainly a helper/diagnostic function." msgstr "" -#: ../../c-api/init.rst:1116 +#: ../../c-api/init.rst:1297 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 +1884,13 @@ msgid "" "otherwise behave differently." msgstr "" -#: ../../c-api/init.rst:1128 +#: ../../c-api/init.rst:1309 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:1315 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 +1902,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:1323 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 +1914,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:1331 msgid "" "This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to :" "c:macro:`Py_END_ALLOW_THREADS` without the closing brace." @@ -1461,7 +1922,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:1337 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 +1932,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:1343 msgid "Low-level API" msgstr "" -#: ../../c-api/init.rst:1164 +#: ../../c-api/init.rst:1345 msgid "" "All of the following functions must be called after :c:func:`Py_Initialize`." msgstr "" -#: ../../c-api/init.rst:1166 +#: ../../c-api/init.rst:1347 msgid ":c:func:`Py_Initialize()` now initializes the :term:`GIL`." msgstr "" -#: ../../c-api/init.rst:1172 +#: ../../c-api/init.rst:1353 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:1357 msgid "" "Raises an :ref:`auditing event ` ``cpython." "PyInterpreterState_New`` with no arguments." @@ -1499,13 +1960,13 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "PyInterpreterState_New`` sem argumentos." -#: ../../c-api/init.rst:1181 +#: ../../c-api/init.rst:1362 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:1365 msgid "" "Raises an :ref:`auditing event ` ``cpython." "PyInterpreterState_Clear`` with no arguments." @@ -1513,160 +1974,177 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython." "PyInterpreterState_Clear`` sem argumentos." -#: ../../c-api/init.rst:1189 +#: ../../c-api/init.rst:1370 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:1377 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:1384 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:1387 msgid "" -"This function now calls the :c:member:`PyThreadState.on_delete` callback. " +"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:1391 +msgid "The :c:member:`!PyThreadState.on_delete` callback was removed." +msgstr "" + +#: ../../c-api/init.rst:1397 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:1404 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:1412 msgid "Get the current frame of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1230 +#: ../../c-api/init.rst:1414 msgid "" "Return a :term:`strong reference`. Return ``NULL`` if no frame is currently " "executing." msgstr "" -#: ../../c-api/init.rst:1233 +#: ../../c-api/init.rst:1417 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:1419 ../../c-api/init.rst:1428 +#: ../../c-api/init.rst:1437 msgid "*tstate* must not be ``NULL``." msgstr "" -#: ../../c-api/init.rst:1242 +#: ../../c-api/init.rst:1426 msgid "" "Get the unique thread state identifier of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1251 +#: ../../c-api/init.rst:1435 msgid "Get the interpreter of the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1260 +#: ../../c-api/init.rst:1444 msgid "Suspend tracing and profiling in the Python thread state *tstate*." msgstr "" -#: ../../c-api/init.rst:1262 +#: ../../c-api/init.rst:1446 msgid "Resume them using the :c:func:`PyThreadState_LeaveTracing` function." msgstr "" -#: ../../c-api/init.rst:1269 +#: ../../c-api/init.rst:1453 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:1456 msgid "" "See also :c:func:`PyEval_SetTrace` and :c:func:`PyEval_SetProfile` functions." msgstr "" -#: ../../c-api/init.rst:1280 +#: ../../c-api/init.rst:1464 msgid "Get the current interpreter." msgstr "" -#: ../../c-api/init.rst:1282 +#: ../../c-api/init.rst:1466 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:1469 ../../c-api/init.rst:1479 +#: ../../c-api/init.rst:1504 msgid "The caller must hold the GIL." msgstr "" -#: ../../c-api/init.rst:1292 +#: ../../c-api/init.rst:1476 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:1486 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:1490 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:1493 +msgid "" +"The returned dictionary is borrowed from the interpreter and is valid until " +"interpreter shutdown." +msgstr "" + +#: ../../c-api/init.rst:1501 +msgid "" +"Return a :term:`strong reference` to the ``__main__`` :ref:`module object " +"` for the given interpreter." +msgstr "" + +#: ../../c-api/init.rst:1511 msgid "Type of a frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1315 +#: ../../c-api/init.rst:1513 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:1516 msgid "The function now takes a *tstate* parameter." msgstr "" -#: ../../c-api/init.rst:1321 +#: ../../c-api/init.rst:1519 msgid "" "The *frame* parameter changed from ``PyFrameObject*`` to " "``_PyInterpreterFrame*``." msgstr "" -#: ../../c-api/init.rst:1326 +#: ../../c-api/init.rst:1524 msgid "Get the frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1328 ../../c-api/init.rst:1336 +#: ../../c-api/init.rst:1526 ../../c-api/init.rst:1534 msgid "See the :pep:`523` \"Adding a frame evaluation API to CPython\"." msgstr "" -#: ../../c-api/init.rst:1334 +#: ../../c-api/init.rst:1532 msgid "Set the frame evaluation function." msgstr "" -#: ../../c-api/init.rst:1343 +#: ../../c-api/init.rst:1541 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 +2153,7 @@ msgid "" "raised and the caller should assume no current thread state is available." msgstr "" -#: ../../c-api/init.rst:1352 +#: ../../c-api/init.rst:1550 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 +2165,33 @@ msgid "" "raises no exceptions." msgstr "" -#: ../../c-api/init.rst:1360 +#: ../../c-api/init.rst:1558 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:1564 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:1574 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:1583 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:1589 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 +2200,17 @@ msgid "" "isn't, a fatal error is reported." msgstr "" -#: ../../c-api/init.rst:1394 +#: ../../c-api/init.rst:1595 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:1602 msgid "Sub-interpreter support" msgstr "" -#: ../../c-api/init.rst:1403 +#: ../../c-api/init.rst:1604 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 +2218,7 @@ msgid "" "to do that." msgstr "" -#: ../../c-api/init.rst:1408 +#: ../../c-api/init.rst:1609 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 +2229,31 @@ msgid "" "returns a pointer to its state." msgstr "" -#: ../../c-api/init.rst:1415 +#: ../../c-api/init.rst:1616 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:1622 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:1628 msgid "Structure fields:" msgstr "Campos de estrutura:" -#: ../../c-api/init.rst:1431 +#: ../../c-api/init.rst:1632 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:1636 msgid "" "If this is ``0`` then :c:member:`~PyInterpreterConfig." "check_multi_interp_extensions` must be ``1`` (non-zero). If this is ``1`` " @@ -1783,44 +2261,44 @@ msgid "" "`PyInterpreterConfig_OWN_GIL`." msgstr "" -#: ../../c-api/init.rst:1443 +#: ../../c-api/init.rst:1644 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:1648 msgid "" "Note that the :mod:`subprocess` module still works when fork is disallowed." msgstr "" -#: ../../c-api/init.rst:1452 +#: ../../c-api/init.rst:1653 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:1658 msgid "" "Note that the :mod:`subprocess` module still works when exec is disallowed." msgstr "" -#: ../../c-api/init.rst:1462 +#: ../../c-api/init.rst:1663 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:1669 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:1676 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 +2307,37 @@ msgid "" "`Py_mod_multiple_interpreters`.)" msgstr "" -#: ../../c-api/init.rst:1482 +#: ../../c-api/init.rst:1683 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:1688 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:1695 msgid "Use the default selection (:c:macro:`PyInterpreterConfig_SHARED_GIL`)." msgstr "" -#: ../../c-api/init.rst:1498 +#: ../../c-api/init.rst:1699 msgid "Use (share) the main interpreter's GIL." msgstr "" -#: ../../c-api/init.rst:1502 +#: ../../c-api/init.rst:1703 msgid "Use the sub-interpreter's own GIL." msgstr "" -#: ../../c-api/init.rst:1504 +#: ../../c-api/init.rst:1705 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:1719 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 +2350,13 @@ msgid "" "underlying file descriptors)." msgstr "" -#: ../../c-api/init.rst:1528 +#: ../../c-api/init.rst:1729 msgid "" "The given *config* controls the options with which the interpreter is " "initialized." msgstr "" -#: ../../c-api/init.rst:1531 +#: ../../c-api/init.rst:1732 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 +2367,7 @@ msgid "" "state." msgstr "" -#: ../../c-api/init.rst:1540 +#: ../../c-api/init.rst:1741 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 +2379,31 @@ msgid "" "released here." msgstr "" -#: ../../c-api/init.rst:1551 +#: ../../c-api/init.rst:1752 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:1755 +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:1770 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 +2411,11 @@ msgid "" "internally on the :c:type:`PyInterpreterState`." msgstr "" -#: ../../c-api/init.rst:1574 +#: ../../c-api/init.rst:1779 msgid "Extension modules are shared between (sub-)interpreters as follows:" msgstr "" -#: ../../c-api/init.rst:1576 +#: ../../c-api/init.rst:1781 msgid "" "For modules using multi-phase initialization, e.g. :c:func:" "`PyModule_FromDefAndSpec`, a separate module object is created and " @@ -1927,7 +2423,7 @@ msgid "" "are shared between these module objects." msgstr "" -#: ../../c-api/init.rst:1582 +#: ../../c-api/init.rst:1787 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 +2435,7 @@ msgid "" "might cause unwanted behavior (see `Bugs and caveats`_ below)." msgstr "" -#: ../../c-api/init.rst:1593 +#: ../../c-api/init.rst:1798 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 +2445,7 @@ msgid "" "shared between these modules." msgstr "" -#: ../../c-api/init.rst:1613 +#: ../../c-api/init.rst:1818 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 +2454,7 @@ msgid "" "single-phase init modules." msgstr "" -#: ../../c-api/init.rst:1625 +#: ../../c-api/init.rst:1830 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 +2464,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:1838 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:1845 msgid "A Per-Interpreter GIL" msgstr "" -#: ../../c-api/init.rst:1640 +#: ../../c-api/init.rst:1847 msgid "" "Using :c:func:`Py_NewInterpreterFromConfig` you can create a sub-interpreter " "that is completely isolated from other interpreters, including having its " @@ -1987,10 +2483,10 @@ msgid "" "interpreters or blocking any others. Thus a single Python process can truly " "take advantage of multiple CPU cores when running Python code. The " "isolation also encourages a different approach to concurrency than that of " -"just using threads. (See :pep:`554`.)" +"just using threads. (See :pep:`554` and :pep:`684`.)" msgstr "" -#: ../../c-api/init.rst:1650 +#: ../../c-api/init.rst:1857 msgid "" "Using an isolated interpreter requires vigilance in preserving that " "isolation. That especially means not sharing any objects or mutable state " @@ -2004,7 +2500,7 @@ msgid "" "builtin objects." msgstr "" -#: ../../c-api/init.rst:1661 +#: ../../c-api/init.rst:1868 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 +2512,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:1873 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 +2522,11 @@ msgid "" "sharing) data between interpreters." msgstr "" -#: ../../c-api/init.rst:1677 +#: ../../c-api/init.rst:1884 msgid "Bugs and caveats" msgstr "" -#: ../../c-api/init.rst:1679 +#: ../../c-api/init.rst:1886 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 +2539,7 @@ msgid "" "should be avoided if possible." msgstr "" -#: ../../c-api/init.rst:1689 +#: ../../c-api/init.rst:1896 msgid "" "Special care should be taken to avoid sharing user-defined functions, " "methods, instances or classes between sub-interpreters, since import " @@ -2052,7 +2548,7 @@ msgid "" "objects from which the above are reachable." msgstr "" -#: ../../c-api/init.rst:1695 +#: ../../c-api/init.rst:1902 msgid "" "Also note that combining this functionality with ``PyGILState_*`` APIs is " "delicate, because these APIs assume a bijection between Python thread states " @@ -2064,25 +2560,25 @@ msgid "" "created threads will probably be broken when using sub-interpreters." msgstr "" -#: ../../c-api/init.rst:1706 +#: ../../c-api/init.rst:1913 msgid "Asynchronous Notifications" msgstr "Notificações assíncronas" -#: ../../c-api/init.rst:1708 +#: ../../c-api/init.rst:1915 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:1922 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:1926 msgid "" "When successfully queued, *func* will be *eventually* called from the main " "interpreter thread with the argument *arg*. It will be called " @@ -2090,17 +2586,17 @@ msgid "" "these conditions met:" msgstr "" -#: ../../c-api/init.rst:1724 +#: ../../c-api/init.rst:1931 msgid "on a :term:`bytecode` boundary;" msgstr "" -#: ../../c-api/init.rst:1725 +#: ../../c-api/init.rst:1932 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:1935 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 +2604,20 @@ msgid "" "if the global interpreter lock is released." msgstr "" -#: ../../c-api/init.rst:1733 +#: ../../c-api/init.rst:1940 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:1943 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:1948 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 +2627,7 @@ msgid "" "`PyGILState API`." msgstr "" -#: ../../c-api/init.rst:1750 +#: ../../c-api/init.rst:1957 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 +2635,23 @@ msgid "" "scheduled calls." msgstr "" -#: ../../c-api/init.rst:1759 +#: ../../c-api/init.rst:1963 +msgid "" +"This function now always schedules *func* to be run in the main interpreter." +msgstr "" + +#: ../../c-api/init.rst:1970 msgid "Profiling and Tracing" msgstr "" -#: ../../c-api/init.rst:1764 +#: ../../c-api/init.rst:1975 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:1979 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 +2661,7 @@ msgid "" "reported to the Python-level trace functions in previous versions." msgstr "" -#: ../../c-api/init.rst:1778 +#: ../../c-api/init.rst:1989 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 +2673,66 @@ msgid "" "value of *what*:" msgstr "" -#: ../../c-api/init.rst:1787 +#: ../../c-api/init.rst:1998 msgid "Value of *what*" msgstr "" -#: ../../c-api/init.rst:1787 +#: ../../c-api/init.rst:1998 msgid "Meaning of *arg*" msgstr "" -#: ../../c-api/init.rst:1789 +#: ../../c-api/init.rst:2000 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:2000 ../../c-api/init.rst:2005 +#: ../../c-api/init.rst:2016 msgid "Always :c:data:`Py_None`." msgstr "" -#: ../../c-api/init.rst:1791 +#: ../../c-api/init.rst:2002 msgid ":c:data:`PyTrace_EXCEPTION`" msgstr "" -#: ../../c-api/init.rst:1791 +#: ../../c-api/init.rst:2002 msgid "Exception information as returned by :func:`sys.exc_info`." msgstr "" -#: ../../c-api/init.rst:1794 +#: ../../c-api/init.rst:2005 msgid ":c:data:`PyTrace_LINE`" msgstr "" -#: ../../c-api/init.rst:1796 +#: ../../c-api/init.rst:2007 msgid ":c:data:`PyTrace_RETURN`" msgstr "" -#: ../../c-api/init.rst:1796 +#: ../../c-api/init.rst:2007 msgid "" "Value being returned to the caller, or ``NULL`` if caused by an exception." msgstr "" -#: ../../c-api/init.rst:1799 +#: ../../c-api/init.rst:2010 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:2010 ../../c-api/init.rst:2012 +#: ../../c-api/init.rst:2014 msgid "Function object being called." msgstr "" -#: ../../c-api/init.rst:1801 +#: ../../c-api/init.rst:2012 msgid ":c:data:`PyTrace_C_EXCEPTION`" msgstr "" -#: ../../c-api/init.rst:1803 +#: ../../c-api/init.rst:2014 msgid ":c:data:`PyTrace_C_RETURN`" msgstr "" -#: ../../c-api/init.rst:1805 +#: ../../c-api/init.rst:2016 msgid ":c:data:`PyTrace_OPCODE`" msgstr "" -#: ../../c-api/init.rst:1810 +#: ../../c-api/init.rst:2021 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 +2741,7 @@ msgid "" "the corresponding frame." msgstr "" -#: ../../c-api/init.rst:1819 +#: ../../c-api/init.rst:2030 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 +2753,7 @@ msgid "" "profiler." msgstr "" -#: ../../c-api/init.rst:1830 +#: ../../c-api/init.rst:2041 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 +2761,31 @@ msgid "" "f_trace_lines` to *0* on that frame." msgstr "" -#: ../../c-api/init.rst:1838 +#: ../../c-api/init.rst:2049 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:2055 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:2061 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:2067 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:2073 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 +2793,7 @@ msgid "" "attr:`~frame.f_trace_opcodes` to *1* on the frame." msgstr "" -#: ../../c-api/init.rst:1870 +#: ../../c-api/init.rst:2081 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 +2803,29 @@ msgid "" "`PyTrace_LINE` :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`." msgstr "" -#: ../../c-api/init.rst:1877 +#: ../../c-api/init.rst:2088 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:2090 ../../c-api/init.rst:2097 +#: ../../c-api/init.rst:2116 ../../c-api/init.rst:2123 msgid "The caller must hold the :term:`GIL`." msgstr "" -#: ../../c-api/init.rst:1883 +#: ../../c-api/init.rst:2094 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:2099 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:2107 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 +2836,28 @@ msgid "" "*what* parameter." msgstr "" -#: ../../c-api/init.rst:1903 +#: ../../c-api/init.rst:2114 msgid "See also the :func:`sys.settrace` function." msgstr "" -#: ../../c-api/init.rst:1909 +#: ../../c-api/init.rst:2120 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:2125 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:2131 msgid "Reference tracing" msgstr "" -#: ../../c-api/init.rst:1926 +#: ../../c-api/init.rst:2137 msgid "" "The type of the trace function registered using :c:func:" "`PyRefTracer_SetTracer`. The first parameter is a Python object that has " @@ -2366,19 +2867,19 @@ msgid "" "provided when :c:func:`PyRefTracer_SetTracer` was called." msgstr "" -#: ../../c-api/init.rst:1936 +#: ../../c-api/init.rst:2147 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:2152 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:2157 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 +2888,7 @@ msgid "" "return ``-1`` on error." msgstr "" -#: ../../c-api/init.rst:1952 +#: ../../c-api/init.rst:2163 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 +2896,11 @@ msgid "" "the tracer function is called." msgstr "" -#: ../../c-api/init.rst:1957 ../../c-api/init.rst:1968 +#: ../../c-api/init.rst:2168 ../../c-api/init.rst:2179 msgid "The GIL must be held when calling this function." msgstr "" -#: ../../c-api/init.rst:1963 +#: ../../c-api/init.rst:2174 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 +2908,48 @@ msgid "" "set the **data** pointer to NULL." msgstr "" -#: ../../c-api/init.rst:1975 +#: ../../c-api/init.rst:2186 msgid "Advanced Debugger Support" msgstr "" -#: ../../c-api/init.rst:1980 +#: ../../c-api/init.rst:2191 msgid "" "These functions are only intended to be used by advanced debugging tools." msgstr "" -#: ../../c-api/init.rst:1985 +#: ../../c-api/init.rst:2196 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:2201 msgid "Return the main interpreter state object." msgstr "" -#: ../../c-api/init.rst:1995 +#: ../../c-api/init.rst:2206 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:2212 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:2218 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:2225 msgid "Thread Local Storage Support" msgstr "" -#: ../../c-api/init.rst:2018 +#: ../../c-api/init.rst:2229 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 +2959,19 @@ msgid "" "thread." msgstr "" -#: ../../c-api/init.rst:2025 +#: ../../c-api/init.rst:2236 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:2239 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:2243 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 +2979,22 @@ msgid "" "don't do refcount operations on them either." msgstr "" -#: ../../c-api/init.rst:2040 +#: ../../c-api/init.rst:2251 msgid "Thread Specific Storage (TSS) API" msgstr "" -#: ../../c-api/init.rst:2042 +#: ../../c-api/init.rst:2253 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:2259 msgid "\"A New C-API for Thread-Local Storage in CPython\" (:pep:`539`)" msgstr "" -#: ../../c-api/init.rst:2053 +#: ../../c-api/init.rst:2264 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 +3002,7 @@ msgid "" "public members in this structure." msgstr "" -#: ../../c-api/init.rst:2058 +#: ../../c-api/init.rst:2269 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 +3010,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:2275 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:2280 msgid "Dynamic Allocation" msgstr "Alocação dinâmica" -#: ../../c-api/init.rst:2071 +#: ../../c-api/init.rst:2282 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:2289 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 +3035,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:2296 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:2302 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:2307 msgid "Methods" msgstr "Métodos" -#: ../../c-api/init.rst:2098 +#: ../../c-api/init.rst:2309 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 +3059,13 @@ msgid "" "func:`PyThread_tss_create`." msgstr "" -#: ../../c-api/init.rst:2106 +#: ../../c-api/init.rst:2317 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:2323 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 +3079,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:2332 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 +3088,31 @@ msgid "" "key -- calling it on an already destroyed key is a no-op." msgstr "" -#: ../../c-api/init.rst:2130 +#: ../../c-api/init.rst:2341 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:2348 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:2356 msgid "Thread Local Storage (TLS) API" msgstr "" -#: ../../c-api/init.rst:2147 +#: ../../c-api/init.rst:2358 msgid "" "This API is superseded by :ref:`Thread Specific Storage (TSS) API `." msgstr "" -#: ../../c-api/init.rst:2152 +#: ../../c-api/init.rst:2363 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 +3121,62 @@ msgid "" "platforms." msgstr "" -#: ../../c-api/init.rst:2157 +#: ../../c-api/init.rst:2368 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:2379 msgid "Synchronization Primitives" msgstr "" -#: ../../c-api/init.rst:2170 +#: ../../c-api/init.rst:2381 msgid "The C-API provides a basic mutual exclusion lock." msgstr "" -#: ../../c-api/init.rst:2174 +#: ../../c-api/init.rst:2385 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:2388 +msgid "PyMutex mutex = {0};" +msgstr "" + +#: ../../c-api/init.rst:2390 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:2396 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:2404 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:2412 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:2420 msgid "Python Critical Section API" msgstr "" -#: ../../c-api/init.rst:2211 +#: ../../c-api/init.rst:2422 msgid "" "The critical section API provides a deadlock avoidance layer on top of per-" "object locks for :term:`free-threaded ` CPython. They are " @@ -2679,17 +3184,27 @@ msgid "" "no-ops in versions of Python with the global interpreter lock." msgstr "" -#: ../../c-api/init.rst:2216 +#: ../../c-api/init.rst:2427 +msgid "" +"Critical sections are intended to be used for custom types implemented in C-" +"API extensions. They should generally not be used with built-in types like :" +"class:`list` and :class:`dict` because their public C-APIs already use " +"critical sections internally, with the notable exception of :c:func:" +"`PyDict_Next`, which requires critical section to be acquired externally." +msgstr "" + +#: ../../c-api/init.rst:2434 msgid "" "Critical sections avoid deadlocks by implicitly suspending active critical " -"sections and releasing the locks during calls to :c:func:" -"`PyEval_SaveThread`. When :c:func:`PyEval_RestoreThread` is called, the most " -"recent critical section is resumed, and its locks reacquired. This means " -"the critical section API provides weaker guarantees than traditional locks " -"-- they are useful because their behavior is similar to the :term:`GIL`." +"sections, hence, they do not provide exclusive access such as provided by " +"traditional locks like :c:type:`PyMutex`. When a critical section is " +"started, the per-object lock for the object is acquired. If the code " +"executed inside the critical section calls C-API functions then it can " +"suspend the critical section thereby releasing the per-object lock, so other " +"threads can acquire the per-object lock for the same object." msgstr "" -#: ../../c-api/init.rst:2223 +#: ../../c-api/init.rst:2442 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 +3212,7 @@ msgid "" "future Python versions." msgstr "" -#: ../../c-api/init.rst:2230 +#: ../../c-api/init.rst:2449 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 +3221,241 @@ msgid "" "lock more than two objects at once." msgstr "" -#: ../../c-api/init.rst:2236 +#: ../../c-api/init.rst:2455 msgid "Example usage::" msgstr "Exemplo de uso::" -#: ../../c-api/init.rst:2247 +#: ../../c-api/init.rst:2457 +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:2466 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:2474 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:2477 ../../c-api/init.rst:2491 +#: ../../c-api/init.rst:2506 ../../c-api/init.rst:2520 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:2479 +msgid "" +"{\n" +" PyCriticalSection _py_cs;\n" +" PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))" +msgstr "" + +#: ../../c-api/init.rst:2483 ../../c-api/init.rst:2512 msgid "In the default build, this macro expands to ``{``." msgstr "" -#: ../../c-api/init.rst:2270 +#: ../../c-api/init.rst:2489 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:2493 +msgid "" +" PyCriticalSection_End(&_py_cs);\n" +"}" +msgstr "" + +#: ../../c-api/init.rst:2496 ../../c-api/init.rst:2525 msgid "In the default build, this macro expands to ``}``." msgstr "" -#: ../../c-api/init.rst:2283 +#: ../../c-api/init.rst:2502 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:2508 +msgid "" +"{\n" +" PyCriticalSection2 _py_cs2;\n" +" PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))" +msgstr "" + +#: ../../c-api/init.rst:2518 msgid "Ends the critical section and releases the per-object locks." msgstr "" -#: ../../c-api/init.rst:335 +#: ../../c-api/init.rst:2522 +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:700 msgid "path (in module sys)" -msgstr "" +msgstr "path (no módulo sys)" -#: ../../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:700 ../../c-api/init.rst:1172 +#: ../../c-api/init.rst:1711 ../../c-api/init.rst:1810 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:1711 ../../c-api/init.rst:1810 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:1711 ../../c-api/init.rst:1810 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:1711 ../../c-api/init.rst:1810 msgid "sys" msgstr "sys" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:700 msgid "search" msgstr "pesquisa" -#: ../../c-api/init.rst:335 ../../c-api/init.rst:576 +#: ../../c-api/init.rst:350 ../../c-api/init.rst:700 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:1775 ../../c-api/init.rst:1828 msgid "Py_FinalizeEx (C function)" msgstr "" -#: ../../c-api/init.rst:445 +#: ../../c-api/init.rst:566 msgid "Py_Initialize()" msgstr "" -#: ../../c-api/init.rst:445 ../../c-api/init.rst:674 +#: ../../c-api/init.rst:566 ../../c-api/init.rst:798 msgid "main()" msgstr "" -#: ../../c-api/init.rst:445 +#: ../../c-api/init.rst:566 msgid "Py_GetPath()" msgstr "" -#: ../../c-api/init.rst:555 +#: ../../c-api/init.rst:679 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:733 ../../c-api/init.rst:775 ../../c-api/init.rst:789 msgid "version (in module sys)" msgstr "" -#: ../../c-api/init.rst:621 +#: ../../c-api/init.rst:745 msgid "platform (in module sys)" msgstr "" -#: ../../c-api/init.rst:638 +#: ../../c-api/init.rst:762 msgid "copyright (in module sys)" msgstr "" -#: ../../c-api/init.rst:674 +#: ../../c-api/init.rst:798 msgid "Py_FatalError()" msgstr "" -#: ../../c-api/init.rst:674 +#: ../../c-api/init.rst:798 msgid "argv (in module sys)" msgstr "" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:918 msgid "global interpreter lock" msgstr "trava global do interpretador" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:918 msgid "interpreter lock" msgstr "" -#: ../../c-api/init.rst:794 +#: ../../c-api/init.rst:918 msgid "lock, interpreter" msgstr "" -#: ../../c-api/init.rst:807 +#: ../../c-api/init.rst:931 msgid "setswitchinterval (in module sys)" msgstr "" -#: ../../c-api/init.rst:816 +#: ../../c-api/init.rst:940 msgid "PyThreadState (C type)" msgstr "" -#: ../../c-api/init.rst:842 +#: ../../c-api/init.rst:966 msgid "Py_BEGIN_ALLOW_THREADS (C macro)" msgstr "" -#: ../../c-api/init.rst:842 +#: ../../c-api/init.rst:966 msgid "Py_END_ALLOW_THREADS (C macro)" msgstr "" -#: ../../c-api/init.rst:858 +#: ../../c-api/init.rst:982 msgid "PyEval_RestoreThread (C function)" msgstr "" -#: ../../c-api/init.rst:858 +#: ../../c-api/init.rst:982 msgid "PyEval_SaveThread (C function)" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1150 msgid "PyEval_AcquireThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1150 msgid "PyEval_ReleaseThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1150 msgid "PyEval_SaveThread()" msgstr "" -#: ../../c-api/init.rst:989 +#: ../../c-api/init.rst:1150 msgid "PyEval_RestoreThread()" msgstr "" -#: ../../c-api/init.rst:1011 +#: ../../c-api/init.rst:1172 msgid "_thread" msgstr "_thread" -#: ../../c-api/init.rst:1510 ../../c-api/init.rst:1605 +#: ../../c-api/init.rst:1711 ../../c-api/init.rst:1810 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:1711 ../../c-api/init.rst:1810 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:1711 ../../c-api/init.rst:1810 msgid "stdin (in module sys)" -msgstr "" +msgstr "stdin (no módulo sys)" -#: ../../c-api/init.rst:1570 +#: ../../c-api/init.rst:1775 msgid "Py_Initialize (C function)" -msgstr "" +msgstr "Py_Initialize (função C)" -#: ../../c-api/init.rst:1600 +#: ../../c-api/init.rst:1805 msgid "close (in module os)" msgstr "" diff --git a/c-api/init_config.po b/c-api/init_config.po index da7753bd2..617fa1a22 100644 --- a/c-api/init_config.po +++ b/c-api/init_config.po @@ -1,32 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Gustavo Reis, 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-11-03 15:10+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Gustavo Reis, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +93,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 +279,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 +514,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 +647,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 +667,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 +704,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" @@ -720,11 +791,11 @@ msgstr "" #: ../../c-api/init_config.rst:502 msgid "Read all Python configuration." -msgstr "" +msgstr "Lê toda a configuração do Python." #: ../../c-api/init_config.rst:504 msgid "Fields which are already initialized are left unchanged." -msgstr "" +msgstr "Campos que já estão inicializados permanecem inalterados." #: ../../c-api/init_config.rst:506 msgid "" @@ -757,7 +828,7 @@ msgstr "" #: ../../c-api/init_config.rst:531 msgid "Release configuration memory." -msgstr "" +msgstr "Libera memória de configuração." #: ../../c-api/init_config.rst:533 msgid "" @@ -883,7 +954,7 @@ msgstr "" #: ../../c-api/init_config.rst:609 msgid "See also :c:member:`PyConfig.exec_prefix`." -msgstr "" +msgstr "Veja também :c:member:`PyConfig.exec_prefix`." #: ../../c-api/init_config.rst:613 msgid "Python base executable: :data:`sys._base_executable`." @@ -1863,19 +1934,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 +1953,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 +2001,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 +2075,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 +2191,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 +2204,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 +2214,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 +2268,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 +2413,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 +2428,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..93b2db3b7 100644 --- a/c-api/intro.po +++ b/c-api/intro.po @@ -1,31 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,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,19 +258,51 @@ 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" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModuleDef_Init(&spam_module);\n" +"}" +msgstr "" +"static struct PyModuleDef spam_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModuleDef_Init(&spam_module);\n" +"}" + #: ../../c-api/intro.rst:134 msgid "Return the absolute value of ``x``." msgstr "Retorna o valor absoluto de ``x``." -#: ../../c-api/intro.rst:140 +#: ../../c-api/intro.rst:136 +msgid "" +"If the result cannot be represented (for example, if ``x`` has :c:macro:`!" +"INT_MIN` value for :c:expr:`int` type), the behavior is undefined." +msgstr "" + +#: ../../c-api/intro.rst:144 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 +#: ../../c-api/intro.rst:147 msgid "" "It can be used to inline performance critical static inline functions when " "building Python in debug mode with function inlining disabled. For example, " @@ -278,7 +313,7 @@ msgstr "" "linha desabilitada. Por exemplo, o MSC desabilita a função de inserir em " "linha ao compilar no modo de depuração." -#: ../../c-api/intro.rst:147 +#: ../../c-api/intro.rst:151 msgid "" "Marking blindly a static inline function with Py_ALWAYS_INLINE can result in " "worse performances (due to increased code size for example). The compiler is " @@ -289,7 +324,7 @@ msgstr "" "exemplo). O compilador geralmente é mais inteligente que o desenvolvedor " "para a análise de custo/benefício." -#: ../../c-api/intro.rst:151 +#: ../../c-api/intro.rst:155 msgid "" "If Python is :ref:`built in debug mode ` (if the :c:macro:" "`Py_DEBUG` macro is defined), the :c:macro:`Py_ALWAYS_INLINE` macro does " @@ -299,11 +334,15 @@ msgstr "" "(se a macro :c:macro:`Py_DEBUG` estiver definida), a macro :c:macro:" "`Py_ALWAYS_INLINE` não fará nada." -#: ../../c-api/intro.rst:154 +#: ../../c-api/intro.rst:158 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:162 +#: ../../c-api/intro.rst:160 +msgid "static inline Py_ALWAYS_INLINE int random(void) { return 4; }" +msgstr "static inline Py_ALWAYS_INLINE int random(void) { return 4; }" + +#: ../../c-api/intro.rst:166 msgid "" "Argument must be a character or an integer in the range [-128, 127] or [0, " "255]. This macro returns ``c`` cast to an ``unsigned char``." @@ -312,7 +351,7 @@ msgstr "" "127] ou [0, 255]. Esta macro retorna ``c`` convertido em um ``unsigned " "char``." -#: ../../c-api/intro.rst:167 +#: ../../c-api/intro.rst:171 msgid "" "Use this for deprecated declarations. The macro must be placed before the " "symbol name." @@ -320,16 +359,20 @@ msgstr "" "Use isso para declarações descontinuadas. A macro deve ser colocada antes do " "nome do símbolo." -#: ../../c-api/intro.rst:170 ../../c-api/intro.rst:256 -#: ../../c-api/intro.rst:274 +#: ../../c-api/intro.rst:174 ../../c-api/intro.rst:283 +#: ../../c-api/intro.rst:301 msgid "Example::" msgstr "Exemplo::" -#: ../../c-api/intro.rst:174 +#: ../../c-api/intro.rst:176 +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:178 msgid "MSVC support was added." msgstr "Suporte a MSVC foi adicionado." -#: ../../c-api/intro.rst:179 +#: ../../c-api/intro.rst:183 msgid "" "Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the " "command line (see :c:member:`PyConfig.use_environment`)." @@ -337,19 +380,19 @@ msgstr "" "Como ``getenv(s)``, mas retorna ``NULL`` se a opção :option:`-E` foi passada " "na linha de comando (veja :c:member:`PyConfig.use_environment`)." -#: ../../c-api/intro.rst:184 +#: ../../c-api/intro.rst:188 msgid "Return the maximum value between ``x`` and ``y``." msgstr "Retorna o valor máximo entre ``x`` e ``y``." -#: ../../c-api/intro.rst:190 +#: ../../c-api/intro.rst:194 msgid "Return the size of a structure (``type``) ``member`` in bytes." msgstr "Retorna o tamanho do ``member`` de uma estrutura (``type``) em bytes." -#: ../../c-api/intro.rst:196 +#: ../../c-api/intro.rst:200 msgid "Return the minimum value between ``x`` and ``y``." msgstr "Retorna o valor mínimo entre ``x`` e ``y``." -#: ../../c-api/intro.rst:202 +#: ../../c-api/intro.rst:206 msgid "" "Disable inlining on a function. For example, it reduces the C stack " "consumption: useful on LTO+PGO builds which heavily inline code (see :issue:" @@ -359,18 +402,22 @@ msgstr "" "consumo da pilha C: útil em compilações LTO+PGO que faz uso intenso de " "inserção em linha de código (veja :issue:`33720`)." -#: ../../c-api/intro.rst:206 +#: ../../c-api/intro.rst:210 msgid "Usage::" msgstr "Uso::" -#: ../../c-api/intro.rst:214 +#: ../../c-api/intro.rst:212 +msgid "Py_NO_INLINE static int random(void) { return 4; }" +msgstr "Py_NO_INLINE static int random(void) { return 4; }" + +#: ../../c-api/intro.rst:218 msgid "" "Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns ``\"123\"``." msgstr "" "Converte ``x`` para uma string C. Por exemplo, ``Py_STRINGIFY(123)`` retorna " "``\"123\"``." -#: ../../c-api/intro.rst:221 +#: ../../c-api/intro.rst:225 msgid "" "Use this when you have a code path that cannot be reached by design. For " "example, in the ``default:`` clause in a ``switch`` statement for which all " @@ -383,7 +430,7 @@ msgstr "" "instruções ``case``. Use isto em lugares onde você pode ficar tentado a " "colocar uma chamada ``assert(0)`` ou ``abort()``." -#: ../../c-api/intro.rst:226 +#: ../../c-api/intro.rst:230 msgid "" "In release mode, the macro helps the compiler to optimize the code, and " "avoids a warning about unreachable code. For example, the macro is " @@ -393,7 +440,7 @@ msgstr "" "evita um aviso sobre código inacessível. Por exemplo, a macro é implementada " "com ``__builtin_unreachable()`` no GCC em modo de lançamento." -#: ../../c-api/intro.rst:230 +#: ../../c-api/intro.rst:234 msgid "" "A use for ``Py_UNREACHABLE()`` is following a call a function that never " "returns but that is not declared :c:macro:`_Py_NO_RETURN`." @@ -401,7 +448,7 @@ msgstr "" "Um uso para ``Py_UNREACHABLE()`` é seguir uma chamada de uma função que " "nunca retorna, mas que não é declarada com :c:macro:`_Py_NO_RETURN`." -#: ../../c-api/intro.rst:233 +#: ../../c-api/intro.rst:237 msgid "" "If a code path is very unlikely code but can be reached under exceptional " "case, this macro must not be used. For example, under low memory condition " @@ -416,7 +463,7 @@ msgstr "" "Se o erro não puder ser reportado ao chamador, :c:func:`Py_FatalError` pode " "ser usada." -#: ../../c-api/intro.rst:243 +#: ../../c-api/intro.rst:247 msgid "" "Use this for unused arguments in a function definition to silence compiler " "warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``." @@ -425,15 +472,41 @@ msgstr "" "silenciar avisos do compilador. Exemplo: ``int func(int a, int Py_UNUSED(b)) " "{ return a; }``." -#: ../../c-api/intro.rst:250 +#: ../../c-api/intro.rst:254 +msgid "" +"Asserts a compile-time condition *cond*, as a statement. The build will fail " +"if the condition is false or cannot be evaluated at compile time." +msgstr "" + +#: ../../c-api/intro.rst:257 ../../c-api/intro.rst:268 +#: ../../c-api/intro.rst:313 +msgid "For example::" +msgstr "Por exemplo::" + +#: ../../c-api/intro.rst:259 +msgid "Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));" +msgstr "" + +#: ../../c-api/intro.rst:265 msgid "" -"Creates a variable with name ``name`` that can be used in docstrings. If " +"Asserts a compile-time condition *cond*, as an expression that evaluates to " +"``0``. The build will fail if the condition is false or cannot be evaluated " +"at compile time." +msgstr "" + +#: ../../c-api/intro.rst:270 +msgid "" +"#define foo_to_char(foo) \\\n" +" ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))" +msgstr "" + +#: ../../c-api/intro.rst:277 +msgid "" +"Creates a variable with name *name* that can be used in docstrings. If " "Python is built without docstrings, the value will be empty." msgstr "" -"Cria uma variável com o nome ``name`` que pode ser usada em docstrings. Se o " -"Python for compilado sem docstrings, o valor estará vazio." -#: ../../c-api/intro.rst:253 +#: ../../c-api/intro.rst:280 msgid "" "Use :c:macro:`PyDoc_STRVAR` for docstrings to support building Python " "without docstrings, as specified in :pep:`7`." @@ -441,7 +514,25 @@ 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:268 +#: ../../c-api/intro.rst:285 +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 "" +"PyDoc_STRVAR(pop_doc, \"Remove e retorna o elemento mais à direita.\");\n" +"\n" +"static PyMethodDef deque_methods[] = {\n" +" // ...\n" +" {\"pop\", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},\n" +" // ...\n" +"}" + +#: ../../c-api/intro.rst:295 msgid "" "Creates a docstring for the given input string or an empty string if " "docstrings are disabled." @@ -449,7 +540,7 @@ msgstr "" "Cria uma docstring para a string de entrada fornecida ou uma string vazia se " "docstrings estiverem desabilitadas." -#: ../../c-api/intro.rst:271 +#: ../../c-api/intro.rst:298 msgid "" "Use :c:macro:`PyDoc_STR` in specifying docstrings to support building Python " "without docstrings, as specified in :pep:`7`." @@ -457,11 +548,37 @@ 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:286 +#: ../../c-api/intro.rst:303 +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 "" +"static PyMethodDef pysqlite_row_methods[] = {\n" +" {\"keys\", (PyCFunction)pysqlite_row_keys, METH_NOARGS,\n" +" PyDoc_STR(\"Retorna as chaves da linha.\")},\n" +" {NULL, NULL}\n" +"};" + +#: ../../c-api/intro.rst:311 +msgid "Declares a static character array variable with the given name *name*." +msgstr "" + +#: ../../c-api/intro.rst:315 +msgid "" +"PyDoc_VAR(python_doc) = PyDoc_STR(\"A genus of constricting snakes in the " +"Pythonidae family native \"\n" +" \"to the tropics and subtropics of the " +"Eastern Hemisphere.\");" +msgstr "" + +#: ../../c-api/intro.rst:322 msgid "Objects, Types and Reference Counts" msgstr "Objetos, tipos e contagens de referências" -#: ../../c-api/intro.rst:290 +#: ../../c-api/intro.rst:326 msgid "" "Most Python/C API functions have one or more arguments as well as a return " "value of type :c:expr:`PyObject*`. This type is a pointer to an opaque data " @@ -488,7 +605,7 @@ msgstr "" "devem ser desalocados, eles são normalmente objetos estáticos :c:type:" "`PyTypeObject`." -#: ../../c-api/intro.rst:301 +#: ../../c-api/intro.rst:337 msgid "" "All Python objects (even Python integers) have a :dfn:`type` and a :dfn:" "`reference count`. An object's type determines what kind of object it is (e." @@ -506,11 +623,11 @@ msgstr "" "um objeto é desse tipo; por exemplo, ``PyList_Check(a)`` é verdadeiro se (e " "somente se) o objeto apontado por *a* for uma lista Python." -#: ../../c-api/intro.rst:312 +#: ../../c-api/intro.rst:348 msgid "Reference Counts" msgstr "Contagens de referências" -#: ../../c-api/intro.rst:314 +#: ../../c-api/intro.rst:350 msgid "" "The reference count is important because today's computers have a finite " "(and often severely limited) memory size; it counts how many different " @@ -524,8 +641,19 @@ msgid "" "objects that reference each other here; for now, the solution is \"don't do " "that.\")" msgstr "" +"A contagem de referências é importante porque os computadores atuais têm um " +"tamanho de memória finito (e frequentemente severamente limitado); ela conta " +"quantos lugares diferentes existem que possuem uma :term:`referência forte` " +"a um objeto. Tal lugar pode ser outro objeto, ou uma variável C global (ou " +"estática), ou uma variável local em alguma função C. Quando a última :term:" +"`referência forte` a um objeto é liberada (ou seja, sua contagem de " +"referências se torna zero), o objeto é desalocado. Se ele contiver " +"referências a outros objetos, essas referências são liberadas. Esses outros " +"objetos podem ser desalocados por sua vez, se não houver mais referências a " +"eles, e assim por diante. (Há um problema óbvio com objetos que referenciam " +"uns aos outros aqui; por enquanto, a solução é \"não faça isso\".)" -#: ../../c-api/intro.rst:331 +#: ../../c-api/intro.rst:367 msgid "" "Reference counts are always manipulated explicitly. The normal way is to " "use the macro :c:func:`Py_INCREF` to take a new reference to an object (i.e. " @@ -543,8 +671,24 @@ msgid "" "``sizeof(Py_ssize_t) >= sizeof(void*)``). Thus, the reference count " "increment is a simple operation." msgstr "" - -#: ../../c-api/intro.rst:347 +"Contagens de referências são sempre manipuladas explicitamente. A maneira " +"normal é usar a macro :c:func:`Py_INCREF` para obter uma nova referência a " +"um objeto (ou seja, incrementar sua contagem de referências em um), e :c:" +"func:`Py_DECREF` para liberar essa referência (ou seja, decrementar a " +"contagem de referências em um). A macro :c:func:`Py_DECREF` é " +"consideravelmente mais complexa do que a incref, pois deve verificar se a " +"contagem de referências se torna zero e, em seguida, fazer com que o " +"desalocador do objeto seja chamado. O desalocador é um ponteiro para função " +"contido na estrutura de tipo do objeto. O desalocador específico do tipo " +"cuida da liberação de referências para outros objetos contidos no objeto se " +"este for um tipo de objeto composto, como uma lista, bem como de executar " +"qualquer finalização adicional necessária. Não há chance de a contagem de " +"referências transbordar; pelo menos tantos bits são usados para armazenar a " +"contagem de referência quantos forem os locais de memória distintos na " +"memória virtual (presumindo ``sizeof(Py_ssize_t) >= sizeof(void*)``). " +"Portanto, o incremento da contagem de referências é uma operação simples." + +#: ../../c-api/intro.rst:383 msgid "" "It is not necessary to hold a :term:`strong reference` (i.e. increment the " "reference count) for every local variable that contains a pointer to an " @@ -561,8 +705,23 @@ msgid "" "that are called from Python; the call mechanism guarantees to hold a " "reference to every argument for the duration of the call." msgstr "" - -#: ../../c-api/intro.rst:363 +"Não é necessário manter uma :term:`referência forte` (ou seja, incrementar a " +"contagem de referências) para cada variável local que contém um ponteiro " +"para um objeto. Em teoria, a contagem de referências do objeto aumenta em um " +"quando a variável é feita para apontar para ele e diminui em um quando a " +"variável sai do escopo. No entanto, esses dois se cancelam, portanto, no " +"final, a contagem de referências não mudou. A única razão real para usar a " +"contagem de referências é evitar que o objeto seja desalocado enquanto nossa " +"variável estiver apontando para ele. Se sabemos que existe pelo menos uma " +"outra referência ao objeto que vive pelo menos tanto quanto nossa variável, " +"não há necessidade de tomar uma nova :term:`referência forte` (ou seja, " +"incrementar a contagem de referências) temporariamente. Uma situação " +"importante em que isso ocorre é em objetos que são passados como argumentos " +"para funções C em um módulo de extensão que são chamados de Python; o " +"mecanismo de chamada garante manter uma referência a todos os argumentos " +"durante a chamada." + +#: ../../c-api/intro.rst:399 msgid "" "However, a common pitfall is to extract an object from a list and hold on to " "it for a while without taking a new reference. Some other operation might " @@ -572,8 +731,16 @@ msgid "" "code path which allows control to flow back to the user from a :c:func:" "`Py_DECREF`, so almost any operation is potentially dangerous." msgstr "" +"No entanto, uma armadilha comum é extrair um objeto de uma lista e mantê-lo " +"por um tempo, sem tomar uma nova referência. Alguma outra operação poderia " +"remover o objeto da lista, liberando essa referência e possivelmente " +"desalocando-o. O perigo real é que operações aparentemente inocentes podem " +"invocar código Python arbitrário que poderia fazer isso; existe um caminho " +"de código que permite que o controle flua de volta para o usuário a partir " +"de um :c:func:`Py_DECREF`, então quase qualquer operação é potencialmente " +"perigosa." -#: ../../c-api/intro.rst:371 +#: ../../c-api/intro.rst:407 msgid "" "A safe approach is to always use the generic operations (functions whose " "name begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or " @@ -582,12 +749,18 @@ msgid "" "This leaves the caller with the responsibility to call :c:func:`Py_DECREF` " "when they are done with the result; this soon becomes second nature." msgstr "" +"Uma abordagem segura é sempre usar as operações genéricas (funções cujo nome " +"começa com ``PyObject_``, ``PyNumber_``, ``PySequence_`` ou ``PyMapping_``). " +"Essas operações sempre criam uma nova :term:`referência forte` (ou seja, " +"incrementam a contagem de referências) do objeto que retornam. Isso deixa o " +"chamador com a responsabilidade de chamar :c:func:`Py_DECREF` quando " +"terminar com o resultado; isso logo se torna uma segunda natureza." -#: ../../c-api/intro.rst:382 +#: ../../c-api/intro.rst:418 msgid "Reference Count Details" msgstr "Detalhes da contagem de referências" -#: ../../c-api/intro.rst:384 +#: ../../c-api/intro.rst:420 msgid "" "The reference count behavior of functions in the Python/C API is best " "explained in terms of *ownership of references*. Ownership pertains to " @@ -603,8 +776,22 @@ msgid "" "said to *borrow* the reference. Nothing needs to be done for a :term:" "`borrowed reference`." msgstr "" - -#: ../../c-api/intro.rst:397 +"O comportamento da contagem de referências de funções na API C/Python é " +"melhor explicado em termos de *propriedade de referências*. A propriedade " +"pertence às referências, nunca aos objetos (os objetos não são possuídos: " +"eles são sempre compartilhados). \"Possuir uma referência\" significa ser " +"responsável por chamar Py_DECREF nela quando a referência não for mais " +"necessária. A propriedade também pode ser transferida, o que significa que o " +"código que recebe a propriedade da referência torna-se responsável por " +"eventualmente efetuar um liberando ela chamando :c:func:`Py_DECREF` ou :c:" +"func:`Py_XDECREF` quando não é mais necessário -- ou passando essa " +"responsabilidade (geralmente para o responsável pela chamada). Quando uma " +"função passa a propriedade de uma referência para seu chamador, diz-se que o " +"chamador recebe uma *nova* referência. Quando nenhuma propriedade é " +"transferida, diz-se que o chamador *toma emprestado* a referência. Nada " +"precisa ser feito para uma :term:`referência emprestada`." + +#: ../../c-api/intro.rst:433 msgid "" "Conversely, when a calling function passes in a reference to an object, " "there are two possibilities: the function *steals* a reference to the " @@ -618,7 +805,7 @@ msgstr "" "referência para uma função, essa função presume que agora ela possui essa " "referência e você não é mais responsável por ela." -#: ../../c-api/intro.rst:407 +#: ../../c-api/intro.rst:443 msgid "" "Few functions steal references; the two notable exceptions are :c:func:" "`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference to " @@ -638,7 +825,23 @@ msgstr "" "(esquecendo o tratamento de erros por enquanto; uma maneira melhor de " "codificar isso é mostrada abaixo)::" -#: ../../c-api/intro.rst:422 +#: ../../c-api/intro.rst:451 +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 "" +"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(\"três\"));" + +#: ../../c-api/intro.rst:458 msgid "" "Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately " "stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object " @@ -651,7 +854,7 @@ msgstr "" "func:`Py_INCREF` para obter outra referência antes de chamar a função de " "roubo de referência." -#: ../../c-api/intro.rst:427 +#: ../../c-api/intro.rst:463 msgid "" "Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple " "items; :c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to " @@ -663,7 +866,7 @@ msgstr "" "recusam a fazer isso, pois tuplas são um tipo de dados imutável. Você só " "deve usar :c:func:`PyTuple_SetItem` para tuplas que você mesmo está criando." -#: ../../c-api/intro.rst:432 +#: ../../c-api/intro.rst:468 msgid "" "Equivalent code for populating a list can be written using :c:func:" "`PyList_New` and :c:func:`PyList_SetItem`." @@ -671,7 +874,7 @@ msgstr "" "O código equivalente para preencher uma lista pode ser escrita usando :c:" "func:`PyList_New` e :c:func:`PyList_SetItem`." -#: ../../c-api/intro.rst:435 +#: ../../c-api/intro.rst:471 msgid "" "However, in practice, you will rarely use these ways of creating and " "populating a tuple or list. There's a generic function, :c:func:" @@ -686,7 +889,19 @@ msgstr "" "código acima podem ser substituídos pelos seguintes (que também cuidam da " "verificação de erros)::" -#: ../../c-api/intro.rst:446 +#: ../../c-api/intro.rst:477 +msgid "" +"PyObject *tuple, *list;\n" +"\n" +"tuple = Py_BuildValue(\"(iis)\", 1, 2, \"three\");\n" +"list = Py_BuildValue(\"[iis]\", 1, 2, \"three\");" +msgstr "" +"PyObject *tuple, *list;\n" +"\n" +"tuple = Py_BuildValue(\"(iis)\", 1, 2, \"três\");\n" +"list = Py_BuildValue(\"[iis]\", 1, 2, \"três\");" + +#: ../../c-api/intro.rst:482 msgid "" "It is much more common to use :c:func:`PyObject_SetItem` and friends with " "items whose references you are only borrowing, like arguments that were " @@ -696,8 +911,59 @@ msgid "" "For example, this function sets all items of a list (actually, any mutable " "sequence) to a given item::" msgstr "" - -#: ../../c-api/intro.rst:476 +"É muito mais comum usar :c:func:`PyObject_SetItem` e amigos com itens cujas " +"referências você está apenas pegando emprestado, como argumentos que foram " +"passados para a função que você está escrevendo. Nesse caso, o comportamento " +"deles em relação às referências é muito mais são, já que você não precisa " +"tomar uma nova referência só para poder doá-la (\"mande-a ser roubada\"). " +"Por exemplo, esta função define todos os itens de uma lista (na verdade, " +"qualquer sequência mutável) para um determinado item::" + +#: ../../c-api/intro.rst:489 +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 "" +"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" +"}" + +#: ../../c-api/intro.rst:512 msgid "" "The situation is slightly different for function return values. While " "passing a reference to most functions does not change your ownership " @@ -719,7 +985,7 @@ msgstr "" "como :c:func:`PyObject_GetItem` e :c:func:`PySequence_GetItem`, sempre " "retornam uma nova referência (o chamador torna-se o dono da referência)." -#: ../../c-api/intro.rst:485 +#: ../../c-api/intro.rst:521 msgid "" "It is important to realize that whether you own a reference returned by a " "function depends on which function you call only --- *the plumage* (the type " @@ -737,7 +1003,7 @@ msgstr "" "func:`PySequence_GetItem` (que leva exatamente os mesmos argumentos), você " "possui uma referência ao objeto retornado." -#: ../../c-api/intro.rst:497 +#: ../../c-api/intro.rst:533 msgid "" "Here is an example of how you could write a function that computes the sum " "of the items in a list of integers; once using :c:func:`PyList_GetItem`, " @@ -747,11 +1013,115 @@ 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:561 +#: ../../c-api/intro.rst:537 +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 "" +"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; /* Não é uma lista */\n" +" for (i = 0; i < n; i++) {\n" +" item = PyList_GetItem(list, i); /* Não pode falhar */\n" +" if (!PyLong_Check(item)) continue; /* Ignora não-inteiros */\n" +" value = PyLong_AsLong(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Inteiro muito grande para caber em um C longo, sai */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" return total;\n" +"}" + +#: ../../c-api/intro.rst:563 +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 "" +"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; /* Não tem comprimento */\n" +" for (i = 0; i < n; i++) {\n" +" item = PySequence_GetItem(sequence, i);\n" +" if (item == NULL)\n" +" return -1; /* Não é uma sequência ou outra falha */\n" +" if (PyLong_Check(item)) {\n" +" value = PyLong_AsLong(item);\n" +" Py_DECREF(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Inteiro muito grande para caber em um C longo, sai */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" else {\n" +" Py_DECREF(item); /* Descartar propriedade de referência */\n" +" }\n" +" }\n" +" return total;\n" +"}" + +#: ../../c-api/intro.rst:597 msgid "Types" msgstr "Tipos" -#: ../../c-api/intro.rst:563 +#: ../../c-api/intro.rst:599 msgid "" "There are few other data types that play a significant role in the Python/C " "API; most are simple C types such as :c:expr:`int`, :c:expr:`long`, :c:expr:" @@ -769,7 +1139,7 @@ msgstr "" "e outro é usado para descrever o valor de um número complexo. Eles serão " "discutidos junto com as funções que os utilizam." -#: ../../c-api/intro.rst:573 +#: ../../c-api/intro.rst:609 msgid "" "A signed integral type such that ``sizeof(Py_ssize_t) == sizeof(size_t)``. " "C99 doesn't define such a thing directly (size_t is an unsigned integral " @@ -781,11 +1151,11 @@ msgstr "" "assinado). Veja :pep:`353` para mais detalhes. ``PY_SSIZE_T_MAX`` é o maior " "valor positivo do tipo :c:type:`Py_ssize_t`." -#: ../../c-api/intro.rst:582 +#: ../../c-api/intro.rst:618 msgid "Exceptions" msgstr "Exceções" -#: ../../c-api/intro.rst:584 +#: ../../c-api/intro.rst:620 msgid "" "The Python programmer only needs to deal with exceptions if specific error " "handling is required; unhandled exceptions are automatically propagated to " @@ -799,7 +1169,7 @@ msgstr "" "até chegarem ao interpretador de nível superior, onde são relatadas ao " "usuário acompanhadas por um traceback (situação da pilha de execução)." -#: ../../c-api/intro.rst:592 +#: ../../c-api/intro.rst:628 msgid "" "For C programmers, however, error checking always has to be explicit. All " "functions in the Python/C API can raise exceptions, unless an explicit claim " @@ -826,7 +1196,7 @@ msgstr "" "para erros com :c:func:`PyErr_Occurred`. Essas exceções são sempre " "documentadas explicitamente." -#: ../../c-api/intro.rst:607 +#: ../../c-api/intro.rst:643 msgid "" "Exception state is maintained in per-thread storage (this is equivalent to " "using global storage in an unthreaded application). A thread can be in one " @@ -848,7 +1218,7 @@ msgstr "" "(embora não a mais geral) para definir o estado de exceção, e :c:func:" "`PyErr_Clear` limpa o estado da exceção." -#: ../../c-api/intro.rst:617 +#: ../../c-api/intro.rst:653 msgid "" "The full exception state consists of three objects (all of which can be " "``NULL``): the exception type, the corresponding exception value, and the " @@ -862,15 +1232,15 @@ 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 +#: ../../c-api/intro.rst:665 msgid "" "Note that starting with Python 1.5, the preferred, thread-safe way to access " "the exception state from Python code is to call the function :func:`sys." @@ -895,7 +1265,7 @@ msgstr "" "indesejada para objetos que são referenciados pelos quadros de pilha no " "traceback." -#: ../../c-api/intro.rst:640 +#: ../../c-api/intro.rst:676 msgid "" "As a general principle, a function that calls another function to perform " "some task should check whether the called function raised an exception, and " @@ -913,7 +1283,7 @@ msgstr "" "acabou de ser gerada e perderia informações importantes sobre a causa exata " "do erro." -#: ../../c-api/intro.rst:649 +#: ../../c-api/intro.rst:685 msgid "" "A simple example of detecting exceptions and passing them on is shown in " "the :c:func:`!sum_sequence` example above. It so happens that this example " @@ -921,12 +1291,121 @@ msgid "" "following example function shows some error cleanup. First, to remind you " "why you like Python, we show the equivalent Python code::" msgstr "" - -#: ../../c-api/intro.rst:664 +"Um exemplo simples de detecção de exceções e transmiti-las é mostrado no " +"exemplo :c:func:`!sum_sequence` acima. Acontece que este exemplo não precisa " +"limpar nenhuma referência de propriedade quando detecta um erro. A função de " +"exemplo a seguir mostra alguma limpeza de erro. Primeiro, para lembrar por " +"que você gosta de Python, mostramos o código Python equivalente::" + +#: ../../c-api/intro.rst:691 +msgid "" +"def incr_item(dict, key):\n" +" try:\n" +" item = dict[key]\n" +" except KeyError:\n" +" item = 0\n" +" dict[key] = item + 1" +msgstr "" +"def incr_item(dict, key):\n" +" try:\n" +" item = dict[key]\n" +" except KeyError:\n" +" item = 0\n" +" dict[key] = item + 1" + +#: ../../c-api/intro.rst:700 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:716 +#: ../../c-api/intro.rst:702 +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 "" +"int\n" +"incr_item(PyObject *dict, PyObject *key)\n" +"{\n" +" /* Objetos todos inicializados para NULL para Py_XDECREF */\n" +" PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;\n" +" int rv = -1; /* Retorna valor inicializado para -1 (falha) */\n" +"\n" +" item = PyObject_GetItem(dict, key);\n" +" if (item == NULL) {\n" +" /* Trata de KeyError apenas: */\n" +" if (!PyErr_ExceptionMatches(PyExc_KeyError))\n" +" goto error;\n" +"\n" +" /* Limpa o erro e usa 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" +" /* Continua com o código de limpeza */\n" +"\n" +" error:\n" +" /* Código de limpeza, compartilhado pelo caminho sucesso e falha */\n" +"\n" +" /* Usa Py_XDECREF() para ignorar referências NULL */\n" +" Py_XDECREF(item);\n" +" Py_XDECREF(const_one);\n" +" Py_XDECREF(incremented_item);\n" +"\n" +" return rv; /* -1 para erro, 0 para sucesso */\n" +"}" + +#: ../../c-api/intro.rst:752 msgid "" "This example represents an endorsed use of the ``goto`` statement in C! It " "illustrates the use of :c:func:`PyErr_ExceptionMatches` and :c:func:" @@ -949,11 +1428,11 @@ msgstr "" "``-1`` (falha) e apenas definido para sucesso após a chamada final feita ser " "bem sucedida." -#: ../../c-api/intro.rst:730 +#: ../../c-api/intro.rst:766 msgid "Embedding Python" msgstr "Incorporando Python" -#: ../../c-api/intro.rst:732 +#: ../../c-api/intro.rst:768 msgid "" "The one important task that only embedders (as opposed to extension writers) " "of the Python interpreter have to worry about is the initialization, and " @@ -966,7 +1445,7 @@ msgstr "" "maior parte da funcionalidade do interpretador só pode ser usada após a " "inicialização do interpretador." -#: ../../c-api/intro.rst:745 +#: ../../c-api/intro.rst:781 msgid "" "The basic initialization function is :c:func:`Py_Initialize`. This " "initializes the table of loaded modules, and creates the fundamental " @@ -978,7 +1457,7 @@ msgstr "" "`builtins`, :mod:`__main__` e :mod:`sys`. Ela também inicializa o caminho de " "pesquisa de módulos (``sys.path``)." -#: ../../c-api/intro.rst:750 +#: ../../c-api/intro.rst:786 msgid "" ":c:func:`Py_Initialize` does not set the \"script argument list\" (``sys." "argv``). If this variable is needed by Python code that will be executed " @@ -991,7 +1470,7 @@ msgstr "" "member:`PyConfig.parse_argv` devem estar definidas; veja :ref:`Configuração " "de inicialização do Python `." -#: ../../c-api/intro.rst:755 +#: ../../c-api/intro.rst:791 msgid "" "On most systems (in particular, on Unix and Windows, although the details " "are slightly different), :c:func:`Py_Initialize` calculates the module " @@ -1012,7 +1491,7 @@ msgstr "" "file:`python` é encontrado no caminho de pesquisa de comandos do shell (a " "variável de ambiente :envvar:`PATH`)." -#: ../../c-api/intro.rst:764 +#: ../../c-api/intro.rst:800 msgid "" "For instance, if the Python executable is found in :file:`/usr/local/bin/" "python`, it will assume that the libraries are in :file:`/usr/local/lib/" @@ -1030,7 +1509,7 @@ msgstr "" "definindo a variável de ambiente :envvar:`PYTHONHOME`, ou insira diretórios " "adicionais na frente do caminho padrão definindo :envvar:`PYTHONPATH`." -#: ../../c-api/intro.rst:778 +#: ../../c-api/intro.rst:814 msgid "" "The embedding application can steer the search by setting :c:member:" "`PyConfig.program_name` *before* calling :c:func:`Py_InitializeFromConfig`. " @@ -1040,8 +1519,15 @@ msgid "" "`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and :c:" "func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`)." msgstr "" +"A aplicação de incorporação pode orientar a pesquisa definindo :c:member:" +"`PyConfig.program_name` *antes* de chamar :c:func:`Py_InitializeFromConfig`. " +"Observe que :envvar:`PYTHONHOME` ainda substitui isso e :envvar:`PYTHONPATH` " +"ainda é inserido na frente do caminho padrão. Uma aplicação que requer " +"controle total deve fornecer sua própria implementação de :c:func:" +"`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix` e :c:func:" +"`Py_GetProgramFullPath` (todas definidas em :file:`Modules/getpath.c`)." -#: ../../c-api/intro.rst:789 +#: ../../c-api/intro.rst:825 msgid "" "Sometimes, it is desirable to \"uninitialize\" Python. For instance, the " "application may want to start over (make another call to :c:func:" @@ -1065,11 +1551,11 @@ msgstr "" "Python, por exemplo, a memória alocada por módulos de extensão atualmente " "não pode ser liberada." -#: ../../c-api/intro.rst:803 +#: ../../c-api/intro.rst:839 msgid "Debugging Builds" msgstr "Compilações de depuração" -#: ../../c-api/intro.rst:805 +#: ../../c-api/intro.rst:841 msgid "" "Python can be built with several macros to enable extra checks of the " "interpreter and extension modules. These checks tend to add a large amount " @@ -1080,7 +1566,7 @@ msgstr "" "adicionar uma grande quantidade de sobrecarga ao tempo de execução, " "portanto, não são habilitadas por padrão." -#: ../../c-api/intro.rst:809 +#: ../../c-api/intro.rst:845 msgid "" "A full list of the various types of debugging builds is in the file :file:" "`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are " @@ -1097,7 +1583,7 @@ msgstr "" "compilações usadas com mais frequência serão descritas no restante desta " "seção." -#: ../../c-api/intro.rst:817 +#: ../../c-api/intro.rst:853 msgid "" "Compiling the interpreter with the :c:macro:`!Py_DEBUG` macro defined " "produces what is generally meant by :ref:`a debug build of Python `. :c:macro:`!Py_DEBUG` é habilitada na construção Unix " +"adicionando :option:`--with-pydebug` ao comando :file:`./configure`. Também " +"está implícito na presença da macro não específica do Python :c:macro:`!" +"_DEBUG`. Quando :c:macro:`!Py_DEBUG` está habilitado na construção do Unix, " +"a otimização do compilador é desabilitada." -#: ../../c-api/intro.rst:825 +#: ../../c-api/intro.rst:861 msgid "" "In addition to the reference count debugging described below, extra checks " "are performed, see :ref:`Python Debug Build `." @@ -1117,7 +1610,7 @@ msgstr "" "extras são realizadas, consulte :ref:`Compilação de Depuração do Python " "`." -#: ../../c-api/intro.rst:828 +#: ../../c-api/intro.rst:864 msgid "" "Defining :c:macro:`Py_TRACE_REFS` enables reference tracing (see the :option:" "`configure --with-trace-refs option <--with-trace-refs>`). When defined, a " @@ -1134,7 +1627,7 @@ msgstr "" "existentes são impressas. (No modo interativo, isso acontece após cada " "instrução executada pelo interpretador.)" -#: ../../c-api/intro.rst:835 +#: ../../c-api/intro.rst:871 msgid "" "Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source " "distribution for more detailed information." @@ -1142,126 +1635,220 @@ msgstr "" "Consulte :file:`Misc/SpecialBuilds.txt` na distribuição do código-fonte " "Python para informações mais detalhadas." -#: ../../c-api/intro.rst:288 +#: ../../c-api/intro.rst:878 +msgid "Recommended third party tools" +msgstr "Ferramentas de terceiros recomendadas" + +#: ../../c-api/intro.rst:880 +msgid "" +"The following third party tools offer both simpler and more sophisticated " +"approaches to creating C, C++ and Rust extensions for Python:" +msgstr "" +"As seguintes ferramentas de terceiros oferecem abordagens mais simples e " +"mais sofisticadas para criar extensões C, C++ e Rust para Python:" + +#: ../../c-api/intro.rst:883 +msgid "`Cython `_" +msgstr "`Cython `_" + +#: ../../c-api/intro.rst:884 +msgid "`cffi `_" +msgstr "`cffi `_" + +#: ../../c-api/intro.rst:885 +msgid "`HPy `_" +msgstr "`HPy `_" + +#: ../../c-api/intro.rst:886 +msgid "`nanobind `_ (C++)" +msgstr "`nanobind `_ (C++)" + +#: ../../c-api/intro.rst:887 +msgid "`Numba `_" +msgstr "`Numba `_" + +#: ../../c-api/intro.rst:888 +msgid "`pybind11 `_ (C++)" +msgstr "`pybind11 `_ (C++)" + +#: ../../c-api/intro.rst:889 +msgid "`PyO3 `_ (Rust)" +msgstr "`PyO3 `_ (Rust)" + +#: ../../c-api/intro.rst:890 +msgid "`SWIG `_" +msgstr "`SWIG `_" + +#: ../../c-api/intro.rst:892 +msgid "" +"Using tools such as these can help avoid writing code that is tightly bound " +"to a particular version of CPython, avoid reference counting errors, and " +"focus more on your own code than on using the CPython API. In general, new " +"versions of Python can be supported by updating the tool, and your code will " +"often use newer and more efficient APIs automatically. Some tools also " +"support compiling for other implementations of Python from a single set of " +"sources." +msgstr "" +"O uso de ferramentas como essas pode ajudar a evitar a criação de código " +"estritamente vinculado a uma versão específica do CPython, evitar erros de " +"contagem de referências e focar mais no seu próprio código do que em usar a " +"API do CPython. Em geral, novas versões do Python podem ser suportadas " +"atualizando a ferramenta, e seu código frequentemente usará APIs mais novas " +"e eficientes automaticamente. Algumas ferramentas também oferecem suporte à " +"compilação para outras implementações do Python a partir de um único " +"conjunto de fontes." + +#: ../../c-api/intro.rst:899 +msgid "" +"These projects are not supported by the same people who maintain Python, and " +"issues need to be raised with the projects directly. Remember to check that " +"the project is still maintained and supported, as the list above may become " +"outdated." +msgstr "" +"Esses projetos não são suportados pelas mesmas pessoas que mantêm o Python, " +"e quaisquer problemas precisam ser relatados diretamente aos projetos. " +"Lembre-se de verificar se o projeto ainda é mantido e tem suporte, pois a " +"lista acima pode ficar desatualizada." + +#: ../../c-api/intro.rst:906 +msgid "" +"`Python Packaging User Guide: Binary Extensions `_" +msgstr "" +"`Guia do Usuário de Empacotamento do Python: Extensões Binárias `_" + +#: ../../c-api/intro.rst:907 +msgid "" +"The Python Packaging User Guide not only covers several available tools that " +"simplify the creation of binary extensions, but also discusses the various " +"reasons why creating an extension module may be desirable in the first place." +msgstr "" +"O Guia do Usuário de Empacotamento do Python não abrange apenas várias " +"ferramentas disponíveis que simplificam a criação de extensões binárias, mas " +"também discute os vários motivos pelos quais a criação de um módulo de " +"extensão pode ser desejável em primeiro lugar." + +#: ../../c-api/intro.rst:324 msgid "object" msgstr "objeto" -#: ../../c-api/intro.rst:288 +#: ../../c-api/intro.rst:324 msgid "type" msgstr "tipo" -#: ../../c-api/intro.rst:327 +#: ../../c-api/intro.rst:363 msgid "Py_INCREF (C function)" -msgstr "" +msgstr "Py_INCREF (função C)" -#: ../../c-api/intro.rst:327 +#: ../../c-api/intro.rst:363 msgid "Py_DECREF (C function)" -msgstr "" +msgstr "Py_DECREF (função C)" -#: ../../c-api/intro.rst:403 +#: ../../c-api/intro.rst:439 msgid "PyList_SetItem (C function)" -msgstr "" +msgstr "PyList_SetItem (função C)" -#: ../../c-api/intro.rst:403 +#: ../../c-api/intro.rst:439 msgid "PyTuple_SetItem (C function)" -msgstr "" +msgstr "PyTuple_SetItem (função C)" -#: ../../c-api/intro.rst:474 +#: ../../c-api/intro.rst:510 msgid "set_all()" -msgstr "" +msgstr "set_all()" -#: ../../c-api/intro.rst:493 +#: ../../c-api/intro.rst:529 msgid "PyList_GetItem (C function)" -msgstr "" +msgstr "PyList_GetItem (função C)" -#: ../../c-api/intro.rst:493 +#: ../../c-api/intro.rst:529 msgid "PySequence_GetItem (C function)" -msgstr "" +msgstr "PySequence_GetItem (função C)" -#: ../../c-api/intro.rst:523 +#: ../../c-api/intro.rst:559 msgid "sum_list()" -msgstr "" +msgstr "sum_list()" -#: ../../c-api/intro.rst:555 ../../c-api/intro.rst:647 +#: ../../c-api/intro.rst:591 ../../c-api/intro.rst:683 msgid "sum_sequence()" -msgstr "" +msgstr "sum_sequence()" -#: ../../c-api/intro.rst:590 +#: ../../c-api/intro.rst:626 msgid "PyErr_Occurred (C function)" -msgstr "" +msgstr "PyErr_Occurred (função C)" -#: ../../c-api/intro.rst:603 +#: ../../c-api/intro.rst:639 msgid "PyErr_SetString (C function)" -msgstr "" +msgstr "PyErr_SetString (função C)" -#: ../../c-api/intro.rst:603 ../../c-api/intro.rst:711 +#: ../../c-api/intro.rst:639 ../../c-api/intro.rst:747 msgid "PyErr_Clear (C function)" -msgstr "" +msgstr "PyErr_Clear (função C)" -#: ../../c-api/intro.rst:627 +#: ../../c-api/intro.rst:663 msgid "exc_info (in module sys)" -msgstr "" +msgstr "exc_info (no módulo sys)" -#: ../../c-api/intro.rst:662 ../../c-api/intro.rst:709 +#: ../../c-api/intro.rst:698 ../../c-api/intro.rst:745 msgid "incr_item()" -msgstr "" +msgstr "incr_item()" -#: ../../c-api/intro.rst:711 +#: ../../c-api/intro.rst:747 msgid "PyErr_ExceptionMatches (C function)" -msgstr "" +msgstr "PyErr_ExceptionMatches (função C)" -#: ../../c-api/intro.rst:711 +#: ../../c-api/intro.rst:747 msgid "Py_XDECREF (C function)" -msgstr "" +msgstr "Py_XDECREF (função C)" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "Py_Initialize (C function)" -msgstr "" +msgstr "Py_Initialize (função C)" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "module" msgstr "módulo" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "builtins" msgstr "builtins" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "__main__" msgstr "__main__" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "sys" msgstr "sys" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "search" msgstr "pesquisa" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "path" msgstr "caminho" -#: ../../c-api/intro.rst:737 +#: ../../c-api/intro.rst:773 msgid "path (in module sys)" -msgstr "" +msgstr "path (no módulo sys)" -#: ../../c-api/intro.rst:772 +#: ../../c-api/intro.rst:808 msgid "Py_GetPath (C function)" -msgstr "" +msgstr "Py_GetPath (função C)" -#: ../../c-api/intro.rst:772 +#: ../../c-api/intro.rst:808 msgid "Py_GetPrefix (C function)" -msgstr "" +msgstr "Py_GetPrefix (função C)" -#: ../../c-api/intro.rst:772 +#: ../../c-api/intro.rst:808 msgid "Py_GetExecPrefix (C function)" -msgstr "" +msgstr "Py_GetExecPrefix (função C)" -#: ../../c-api/intro.rst:772 +#: ../../c-api/intro.rst:808 msgid "Py_GetProgramFullPath (C function)" -msgstr "" +msgstr "Py_GetProgramFullPath (função C)" -#: ../../c-api/intro.rst:787 +#: ../../c-api/intro.rst:823 msgid "Py_IsInitialized (C function)" -msgstr "" +msgstr "Py_IsInitialized (função C)" diff --git a/c-api/iter.po b/c-api/iter.po index a4f8785d6..a043a8be6 100644 --- a/c-api/iter.po +++ b/c-api/iter.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +70,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`." @@ -93,7 +140,7 @@ msgstr "" msgid "" "``PYGEN_NEXT`` if iterator yields. Yielded value is returned via *presult*." msgstr "" -"``PYGEN_NEXT`` se o iterador render. O valor preduzido é retornado via " +"``PYGEN_NEXT`` se o iterador render. O valor produzido é retornado via " "*presult*." #: ../../c-api/iter.rst:70 diff --git a/c-api/iterator.po b/c-api/iterator.po index e0c26f3c4..f3db353e9 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 +# python-doc bot, 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,3 +97,77 @@ msgstr "" "qualquer objeto chamável do Python que possa ser chamado sem parâmetros; " "cada chamada deve retornar o próximo item na iteração. Quando *callable* " "retorna um valor igual a *sentinel*, a iteração será encerrada." + +#: ../../c-api/iterator.rst:56 +msgid "Range Objects" +msgstr "" + +#: ../../c-api/iterator.rst:60 +msgid "The type object for :class:`range` objects." +msgstr "" + +#: ../../c-api/iterator.rst:65 +msgid "" +"Return true if the object *o* is an instance of a :class:`range` object. " +"This function always succeeds." +msgstr "" + +#: ../../c-api/iterator.rst:70 +msgid "Builtin Iterator Types" +msgstr "" + +#: ../../c-api/iterator.rst:72 +msgid "" +"These are built-in iteration types that are included in Python's C API, but " +"provide no additional functions. They are here for completeness." +msgstr "" + +#: ../../c-api/iterator.rst:80 +msgid "C type" +msgstr "Tipo em C" + +#: ../../c-api/iterator.rst:81 +msgid "Python type" +msgstr "Tipo em Python" + +#: ../../c-api/iterator.rst:83 +msgid ":py:class:`enumerate`" +msgstr "" + +#: ../../c-api/iterator.rst:85 +msgid ":py:class:`filter`" +msgstr "" + +#: ../../c-api/iterator.rst:87 +msgid ":py:class:`map`" +msgstr "" + +#: ../../c-api/iterator.rst:89 +msgid ":py:class:`reversed`" +msgstr "" + +#: ../../c-api/iterator.rst:91 +msgid ":py:class:`zip`" +msgstr "" + +#: ../../c-api/iterator.rst:95 +msgid "Other Iterator Objects" +msgstr "" + +#: ../../c-api/iterator.rst:112 +msgid "Type objects for iterators of various built-in objects." +msgstr "" + +#: ../../c-api/iterator.rst:114 +msgid "" +"Do not create instances of these directly; prefer calling :c:func:" +"`PyObject_GetIter` instead." +msgstr "" + +#: ../../c-api/iterator.rst:117 +msgid "" +"Note that there is no guarantee that a given built-in type uses a given " +"iterator type. For example, iterating over :class:`range` will use one of " +"two iterator types depending on the size of the range. Other types may start " +"using a similar scheme in the future, without warning." +msgstr "" diff --git a/c-api/list.po b/c-api/list.po index 66f5bbba3..f7feed04a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c9b52c1f3 100644 --- a/c-api/long.po +++ b/c-api/long.po @@ -1,29 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,20 +81,22 @@ msgstr "" "Retorna um novo objeto :c:type:`PyLongObject` de *v* ou ``NULL`` em caso de " "falha." -#: ../../c-api/long.rst:43 +#: ../../c-api/long.rst:45 msgid "" -"The current implementation keeps an array of integer objects for all " -"integers between ``-5`` and ``256``. When you create an int in that range " -"you actually just get back a reference to the existing object." +"CPython keeps an array of integer objects for all integers between ``-5`` " +"and ``256``. When you create an int in that range you actually just get " +"back a reference to the existing object." msgstr "" -#: ../../c-api/long.rst:50 +#: ../../c-api/long.rst:52 msgid "" "Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long`, " "or ``NULL`` on failure." msgstr "" +"Retorna um novo objeto :c:type:`PyLongObject` de um :c:expr:`unsigned long` " +"C ou ``NULL`` em caso de falha." -#: ../../c-api/long.rst:56 +#: ../../c-api/long.rst:58 msgid "" "Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or " "``NULL`` on failure." @@ -105,7 +104,7 @@ msgstr "" "Retorna um novo objeto :c:type:`PyLongObject` de um :c:type:`Py_ssize_t` C " "ou ``NULL`` em caso de falha." -#: ../../c-api/long.rst:62 +#: ../../c-api/long.rst:64 msgid "" "Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or " "``NULL`` on failure." @@ -113,19 +112,23 @@ msgstr "" "Retorna um novo objeto :c:type:`PyLongObject` de um :c:type:`size_t` C ou " "``NULL`` em caso de falha." -#: ../../c-api/long.rst:68 +#: ../../c-api/long.rst:70 msgid "" "Return a new :c:type:`PyLongObject` object from a C :c:expr:`long long`, or " "``NULL`` on failure." msgstr "" +"Retorna um novo objeto :c:type:`PyLongObject` de um :c:expr:`long long` C ou " +"``NULL`` em caso de falha." -#: ../../c-api/long.rst:74 +#: ../../c-api/long.rst:76 msgid "" "Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long " "long`, or ``NULL`` on failure." msgstr "" +"Retorna um novo objeto :c:type:`PyLongObject` de um :c:expr:`unsigned long " +"long` C ou ``NULL`` em caso de falha." -#: ../../c-api/long.rst:80 +#: ../../c-api/long.rst:82 msgid "" "Return a new :c:type:`PyLongObject` object from the integer part of *v*, or " "``NULL`` on failure." @@ -133,7 +136,7 @@ msgstr "" "Retorna um novo objeto :c:type:`PyLongObject` da parte inteira de *v* ou " "``NULL`` em caso de falha." -#: ../../c-api/long.rst:86 +#: ../../c-api/long.rst:88 msgid "" "Return a new :c:type:`PyLongObject` based on the string value in *str*, " "which is interpreted according to the radix in *base*, or ``NULL`` on " @@ -147,15 +150,27 @@ msgid "" "digits or *str* is not NULL-terminated following the digits and trailing " "whitespace, :exc:`ValueError` will be raised." msgstr "" - -#: ../../c-api/long.rst:97 +"Retorna um novo :c:type:`PyLongObject` com base no valor da string em *str*, " +"que é interpretado de acordo com a raiz em *base* ou ``NULL`` em caso de " +"falha. Se *pend* não for ``NULL``, *\\*pend* apontará para o fim do *str* em " +"caso de sucesso ou para seu primeiro caractere que não pode ser processado " +"em caso de erro. Se *base* for ``0``, *str* é interpretado usando a " +"definição de :ref:`integers`; neste caso, zeros à esquerda em um número " +"decimal diferente de zero aumenta um :exc:`ValueError`. Se *base* não for " +"``0``, deve estar entre ``2`` e ``36``, inclusive. Espaços em branco no " +"início ou no final e sublinhados simples após um especificador de base e " +"entre dígitos são ignorados. Se não houver dígitos ou *str* não for " +"terminado em NULL após os dígitos e espaços em branco à direita, :exc:" +"`ValueError` será levantada." + +#: ../../c-api/long.rst:99 msgid "" "Python methods :meth:`int.to_bytes` and :meth:`int.from_bytes` to convert a :" "c:type:`PyLongObject` to/from an array of bytes in base ``256``. You can " "call those from C using :c:func:`PyObject_CallMethod`." msgstr "" -#: ../../c-api/long.rst:104 +#: ../../c-api/long.rst:106 msgid "" "Convert a sequence of Unicode digits in the string *u* to a Python integer " "value." @@ -163,7 +178,7 @@ msgstr "" "Converte uma sequência de dígitos Unicode na string *u* para um valor " "inteiro Python." -#: ../../c-api/long.rst:112 +#: ../../c-api/long.rst:114 msgid "" "Create a Python integer from the pointer *p*. The pointer value can be " "retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`." @@ -171,13 +186,13 @@ msgstr "" "Cria um inteiro Python a partir do ponteiro *p*. O valor do ponteiro pode " "ser recuperado do valor resultante usando :c:func:`PyLong_AsVoidPtr`." -#: ../../c-api/long.rst:118 +#: ../../c-api/long.rst:120 msgid "" "Create a Python integer from the value contained in the first *n_bytes* of " "*buffer*, interpreted as a two's-complement signed number." msgstr "" -#: ../../c-api/long.rst:121 +#: ../../c-api/long.rst:123 msgid "" "*flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will " "select the native endian that CPython was compiled with and assume that the " @@ -186,56 +201,77 @@ msgid "" "calling :c:func:`PyLong_FromUnsignedNativeBytes`. Other flags are ignored." msgstr "" -#: ../../c-api/long.rst:132 +#: ../../c-api/long.rst:134 msgid "" "Create a Python integer from the value contained in the first *n_bytes* of " "*buffer*, interpreted as an unsigned number." msgstr "" -#: ../../c-api/long.rst:135 +#: ../../c-api/long.rst:137 msgid "" "*flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will " "select the native endian that CPython was compiled with and assume that the " "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:146 +msgid "Macro for creating a Python integer from a process identifier." +msgstr "" + +#: ../../c-api/long.rst:148 +msgid "" +"This can be defined as an alias to :c:func:`PyLong_FromLong` or :c:func:" +"`PyLong_FromLongLong`, depending on the size of the system's PID type." +msgstr "" + +#: ../../c-api/long.rst:161 ../../c-api/long.rst:197 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:165 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:168 ../../c-api/long.rst:206 ../../c-api/long.rst:227 +#: ../../c-api/long.rst:247 ../../c-api/long.rst:270 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:170 ../../c-api/long.rst:208 ../../c-api/long.rst:229 +#: ../../c-api/long.rst:251 ../../c-api/long.rst:335 ../../c-api/long.rst:355 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:173 ../../c-api/long.rst:211 ../../c-api/long.rst:232 +#: ../../c-api/long.rst:254 ../../c-api/long.rst:338 ../../c-api/long.rst:358 msgid "This function will no longer use :meth:`~object.__int__`." msgstr "" -#: ../../c-api/long.rst:167 +#: ../../c-api/long.rst:180 +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:184 +msgid "The function is soft deprecated." +msgstr "" + +#: ../../c-api/long.rst:189 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:201 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 +279,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:220 ../../c-api/long.rst:238 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:224 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:242 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 +300,7 @@ msgid "" "exception occurs set *\\*overflow* to ``0`` and return ``-1`` as usual." msgstr "" -#: ../../c-api/long.rst:242 +#: ../../c-api/long.rst:264 msgid "" "Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must " "be an instance of :c:type:`PyLongObject`." @@ -272,7 +308,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:267 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "type:`Py_ssize_t`." @@ -280,19 +316,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:279 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:282 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:285 msgid "" "Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -300,7 +336,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:295 msgid "" "Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be an " "instance of :c:type:`PyLongObject`." @@ -308,7 +344,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:298 msgid "" "Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:" "type:`size_t`." @@ -316,7 +352,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:301 msgid "" "Returns ``(size_t)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -324,19 +360,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:310 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:313 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:316 msgid "" "Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -344,27 +380,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:319 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:325 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:329 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:332 msgid "" "Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to " "disambiguate." @@ -372,20 +408,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:344 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:349 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:352 msgid "" "Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` " "to disambiguate." @@ -393,26 +429,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:364 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:367 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:370 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:375 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,142 +456,201 @@ msgid "" "c:func:`PyLong_FromVoidPtr`." msgstr "" -#: ../../c-api/long.rst:358 +#: ../../c-api/long.rst:380 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:385 +msgid "Macro for converting a Python integer into a process identifier." +msgstr "" + +#: ../../c-api/long.rst:387 +msgid "" +"This can be defined as an alias to :c:func:`PyLong_AsLong`, :c:func:" +"`PyLong_FromLongLong`, or :c:func:`PyLong_AsInt`, depending on the size of " +"the system's PID type." +msgstr "" + +#: ../../c-api/long.rst:396 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:400 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:404 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:409 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, " -"and the higher bits are ignored. This matches the typical behavior of a C-" -"style downcast." +"If the returned value is greater than *n_bytes*, the value was truncated: as " +"many of the lowest bits of the value as could fit are written, and the " +"higher bits are ignored. This matches the typical behavior of a C-style " +"downcast." msgstr "" -#: ../../c-api/long.rst:383 +#: ../../c-api/long.rst:416 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:419 msgid "``0`` will never be returned." msgstr "" -#: ../../c-api/long.rst:388 +#: ../../c-api/long.rst:421 msgid "Values are always copied as two's-complement." msgstr "" -#: ../../c-api/long.rst:390 +#: ../../c-api/long.rst:423 msgid "Usage example::" msgstr "" -#: ../../c-api/long.rst:406 +#: ../../c-api/long.rst:425 +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:439 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:446 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:449 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:452 +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:480 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:485 msgid "" "Currently, ``-1`` corresponds to ``Py_ASNATIVEBYTES_NATIVE_ENDIAN | " "Py_ASNATIVEBYTES_UNSIGNED_BUFFER``." msgstr "" -#: ../../c-api/long.rst:456 +#: ../../c-api/long.rst:491 msgid "Flag" msgstr "Sinalizador" -#: ../../c-api/long.rst:456 +#: ../../c-api/long.rst:491 msgid "Value" msgstr "Valor" -#: ../../c-api/long.rst:458 +#: ../../c-api/long.rst:493 msgid "``-1``" -msgstr "" +msgstr "``-1``" -#: ../../c-api/long.rst:459 +#: ../../c-api/long.rst:494 msgid "``0``" msgstr "``0``" -#: ../../c-api/long.rst:460 +#: ../../c-api/long.rst:495 msgid "``1``" msgstr "``1``" -#: ../../c-api/long.rst:461 +#: ../../c-api/long.rst:496 msgid "``3``" msgstr "``3``" -#: ../../c-api/long.rst:462 +#: ../../c-api/long.rst:497 msgid "``4``" msgstr "``4``" -#: ../../c-api/long.rst:463 +#: ../../c-api/long.rst:498 msgid "``8``" msgstr "``8``" -#: ../../c-api/long.rst:464 +#: ../../c-api/long.rst:499 msgid "``16``" -msgstr "" +msgstr "``16``" -#: ../../c-api/long.rst:467 +#: ../../c-api/long.rst:502 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:505 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:509 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 +660,7 @@ msgid "" "requested." msgstr "" -#: ../../c-api/long.rst:481 +#: ../../c-api/long.rst:516 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 +668,7 @@ msgid "" "of whether ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` was specified." msgstr "" -#: ../../c-api/long.rst:486 +#: ../../c-api/long.rst:521 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 +678,7 @@ msgid "" "`TypeError`." msgstr "" -#: ../../c-api/long.rst:495 +#: ../../c-api/long.rst:530 msgid "" "With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without " "*REJECT_NEGATIVE*), multiple Python integers can map to a single value " @@ -591,22 +686,22 @@ msgid "" "buffer and set all its bits. This matches typical C cast behavior." msgstr "" -#: ../../c-api/long.rst:506 +#: ../../c-api/long.rst:541 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:545 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:552 msgid "Return 1 if *op* is compact, 0 otherwise." msgstr "" -#: ../../c-api/long.rst:519 +#: ../../c-api/long.rst:554 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 +709,23 @@ msgid "" "`PyLong_As* ` function or :c:func:`PyLong_AsNativeBytes`." msgstr "" -#: ../../c-api/long.rst:525 +#: ../../c-api/long.rst:560 msgid "The speedup is expected to be negligible for most users." msgstr "" -#: ../../c-api/long.rst:527 +#: ../../c-api/long.rst:562 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:570 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:573 msgid "Otherwise, the return value is undefined." msgstr "" @@ -646,23 +741,23 @@ msgstr "" msgid "integer" msgstr "inteiro" -#: ../../c-api/long.rst:145 +#: ../../c-api/long.rst:157 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:157 ../../c-api/long.rst:217 ../../c-api/long.rst:260 +#: ../../c-api/long.rst:275 ../../c-api/long.rst:291 ../../c-api/long.rst:307 msgid "OverflowError (built-in exception)" msgstr "" -#: ../../c-api/long.rst:238 +#: ../../c-api/long.rst:260 msgid "PY_SSIZE_T_MAX (C macro)" msgstr "" -#: ../../c-api/long.rst:253 +#: ../../c-api/long.rst:275 msgid "ULONG_MAX (C macro)" msgstr "" -#: ../../c-api/long.rst:269 +#: ../../c-api/long.rst:291 msgid "SIZE_MAX (C macro)" msgstr "" diff --git a/c-api/mapping.po b/c-api/mapping.po index f6c29fcdd..7cfd64156 100644 --- a/c-api/mapping.po +++ b/c-api/mapping.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,15 +156,15 @@ msgstr "" #: ../../c-api/mapping.rst:105 msgid "" -"Exceptions which occur when this calls :meth:`~object.__getitem__` method " -"are silently ignored. For proper error handling, use :c:func:" +"Exceptions which occur when this calls the :meth:`~object.__getitem__` " +"method are silently ignored. For proper error handling, use :c:func:" "`PyMapping_HasKeyWithError`, :c:func:`PyMapping_GetOptionalItem` or :c:func:" "`PyObject_GetItem()` instead." msgstr "" -"As exceções que ocorrem quando esse método chama :meth:`~object.__getitem__` " -"são silenciosamente ignoradas. Para o tratamento adequado de erros, use :c:" -"func:`PyMapping_HasKeyWithError`, :c:func:`PyMapping_GetOptionalItem` ou :c:" -"func:`PyObject_GetItem()` em vez disso." +"As exceções que ocorrem quando este construtor chama o método :meth:`~object." +"__getitem__` são silenciosamente ignoradas. Para o tratamento adequado de " +"erros, use :c:func:`PyMapping_HasKeyWithError`, :c:func:" +"`PyMapping_GetOptionalItem` ou :c:func:`PyObject_GetItem()` em vez disso." #: ../../c-api/mapping.rst:113 msgid "" @@ -177,15 +178,15 @@ msgstr "" #: ../../c-api/mapping.rst:119 msgid "" -"Exceptions that occur when this calls :meth:`~object.__getitem__` method or " -"while creating the temporary :class:`str` object are silently ignored. For " -"proper error handling, use :c:func:`PyMapping_HasKeyStringWithError`, :c:" +"Exceptions that occur when this calls the :meth:`~object.__getitem__` method " +"or while creating the temporary :class:`str` object are silently ignored. " +"For proper error handling, use :c:func:`PyMapping_HasKeyStringWithError`, :c:" "func:`PyMapping_GetOptionalItemString` or :c:func:`PyMapping_GetItemString` " "instead." msgstr "" -"As exceções que ocorrem quando esse método chama :meth:`~object.__getitem__` " -"ou ao criar o objeto temporário :class:`str` são silenciosamente ignoradas. " -"Para o tratamento adequado de erros, use :c:func:" +"As exceções que ocorrem quando este construtor chama o método :meth:`~object." +"__getitem__` ou ao criar o objeto temporário :class:`str` são " +"silenciosamente ignoradas. Para o tratamento adequado de erros, use :c:func:" "`PyMapping_HasKeyStringWithError`, :c:func:`PyMapping_GetOptionalItemString` " "ou :c:func:`PyMapping_GetItemString` em vez disso." diff --git a/c-api/marshal.po b/c-api/marshal.po index 48ff06ffb..e3b1df81c 100644 --- a/c-api/marshal.po +++ b/c-api/marshal.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -152,7 +153,7 @@ msgid "" "assumes that no further objects will be read from the file, allowing it to " "aggressively load file data into memory so that the de-serialization can " "operate from data in memory rather than reading a byte at a time from the " -"file. Only use these variant if you are certain that you won't be reading " +"file. Only use this variant if you are certain that you won't be reading " "anything else from the file." msgstr "" "Retorna um objeto Python do fluxo de dados em um :c:expr:`FILE*` aberto para " @@ -160,7 +161,7 @@ msgstr "" "função presume que nenhum objeto adicional será lido do arquivo, permitindo " "que ela carregue agressivamente os dados do arquivo na memória, para que a " "desserialização possa operar a partir de dados na memória em vez de ler um " -"byte por vez do arquivo. Use essas variantes apenas se tiver certeza de que " +"byte por vez do arquivo. Use essa variante apenas se tiver certeza de que " "não estará lendo mais nada do arquivo." #: ../../c-api/marshal.rst:93 diff --git a/c-api/memory.po b/c-api/memory.po index 6110fa5b4..25c0f30f5 100644 --- a/c-api/memory.po +++ b/c-api/memory.po @@ -1,31 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +40,12 @@ msgid "" "different components which deal with various dynamic storage management " "aspects, like sharing, segmentation, preallocation or caching." msgstr "" +"O gerenciamento de memória em Python envolve um heap privado contendo todos " +"os objetos e estruturas de dados Python. O gerenciamento desse heap privado " +"é garantido internamente pelo *gerenciador de memória do Python*. O " +"gerenciador de memória do Python possui diferentes componentes que lidam com " +"diversos aspectos dinâmicos do gerenciamento de armazenamento, como " +"compartilhamento, segmentação, pré-alocação ou cache." #: ../../c-api/memory.rst:25 msgid "" @@ -59,6 +60,18 @@ msgid "" "manager thus delegates some of the work to the object-specific allocators, " "but ensures that the latter operate within the bounds of the private heap." msgstr "" +"No nível mais baixo, um alocador de memória bruta garante que haja espaço " +"suficiente no heap privado para armazenar todos os dados relacionados ao " +"Python, interagindo com o gerenciador de memória do sistema operacional. " +"Além do alocador de memória bruta, vários alocadores específicos de objeto " +"operam no mesmo heap e implementam políticas distintas de gerenciamento de " +"memória, adaptadas às peculiaridades de cada tipo de objeto. Por exemplo, " +"objetos inteiros são gerenciados dentro do heap de forma diferente de " +"strings, tuplas ou dicionários, pois inteiros implicam diferentes requisitos " +"de armazenamento e compensações entre velocidade e espaço. O gerenciador de " +"memória do Python, portanto, delega parte do trabalho aos alocadores " +"específicos de objeto, mas garante que estes operem dentro dos limites do " +"heap privado." #: ../../c-api/memory.rst:36 msgid "" @@ -82,6 +95,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 " @@ -131,60 +157,71 @@ msgid "" "allocation strategies and are optimized for different purposes. The specific " "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." +"purposes a simplified table can be found at :ref:`default-memory-" +"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 +229,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 +293,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 +367,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,53 +388,58 @@ 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 " "above. However, note that their use does not preserve binary compatibility " "across Python versions and is therefore deprecated in extension modules." msgstr "" +"Além disso, os seguintes conjuntos de macros são fornecidos para chamar o " +"alocador de memória do Python diretamente, sem envolver as funções da API C " +"listadas acima. No entanto, observe que seu uso não preserva a " +"compatibilidade binária entre as versões do Python e, portanto, está " +"descontinuado em módulos de extensão." -#: ../../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 "" +msgstr "``PyMem_RESIZE(ptr, type, size)``" -#: ../../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 +447,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 +495,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 "" +msgstr "Legenda:" -#: ../../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:674 msgid "Field" msgstr "Campo" -#: ../../c-api/memory.rst:413 ../../c-api/memory.rst:660 +#: ../../c-api/memory.rst:423 ../../c-api/memory.rst:674 msgid "Meaning" msgstr "Significado" -#: ../../c-api/memory.rst:415 ../../c-api/memory.rst:662 +#: ../../c-api/memory.rst:425 ../../c-api/memory.rst:676 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:676 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 +781,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 +789,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 +811,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 +833,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 +859,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 +867,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 +877,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 +930,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 +958,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 +971,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 +980,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 +988,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 +1001,82 @@ 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:659 +msgid "" +"Typically, it makes sense to disable the pymalloc allocator when building " +"Python with AddressSanitizer (:option:`--with-address-sanitizer`) which " +"helps uncover low level bugs within the C code." +msgstr "" + +#: ../../c-api/memory.rst:664 msgid "Customize pymalloc Arena Allocator" msgstr "" -#: ../../c-api/memory.rst:656 +#: ../../c-api/memory.rst:670 msgid "" "Structure used to describe an arena allocator. The structure has three " "fields:" msgstr "" -#: ../../c-api/memory.rst:664 +#: ../../c-api/memory.rst:678 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:678 msgid "allocate an arena of size bytes" msgstr "" -#: ../../c-api/memory.rst:666 +#: ../../c-api/memory.rst:680 msgid "``void free(void *ctx, void *ptr, size_t size)``" -msgstr "" +msgstr "``void free(void *ctx, void *ptr, size_t size)``" -#: ../../c-api/memory.rst:666 +#: ../../c-api/memory.rst:680 msgid "free an arena" msgstr "" -#: ../../c-api/memory.rst:671 +#: ../../c-api/memory.rst:685 msgid "Get the arena allocator." msgstr "" -#: ../../c-api/memory.rst:675 +#: ../../c-api/memory.rst:689 msgid "Set the arena allocator." msgstr "" -#: ../../c-api/memory.rst:680 +#: ../../c-api/memory.rst:694 msgid "The mimalloc allocator" msgstr "" -#: ../../c-api/memory.rst:684 +#: ../../c-api/memory.rst:698 msgid "" "Python supports the mimalloc allocator when the underlying platform support " "is available. mimalloc \"is a general purpose allocator with excellent " @@ -1035,50 +1084,76 @@ msgid "" "runtime systems of the Koka and Lean languages.\"" msgstr "" -#: ../../c-api/memory.rst:689 +#: ../../c-api/memory.rst:703 msgid "tracemalloc C API" msgstr "" -#: ../../c-api/memory.rst:695 +#: ../../c-api/memory.rst:709 msgid "Track an allocated memory block in the :mod:`tracemalloc` module." msgstr "" -#: ../../c-api/memory.rst:697 +#: ../../c-api/memory.rst:711 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:714 msgid "If memory block is already tracked, update the existing trace." msgstr "" -#: ../../c-api/memory.rst:704 +#: ../../c-api/memory.rst:718 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:721 msgid "Return ``-2`` if tracemalloc is disabled, otherwise return ``0``." msgstr "" -#: ../../c-api/memory.rst:713 +#: ../../c-api/memory.rst:727 msgid "Examples" msgstr "Exemplos" -#: ../../c-api/memory.rst:715 +#: ../../c-api/memory.rst:729 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 " "set::" msgstr "" -#: ../../c-api/memory.rst:728 +#: ../../c-api/memory.rst:732 +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:742 msgid "The same code using the type-oriented function set::" msgstr "" -#: ../../c-api/memory.rst:740 +#: ../../c-api/memory.rst:744 +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:754 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 " @@ -1088,14 +1163,25 @@ msgid "" "different allocators operating on different heaps. ::" msgstr "" -#: ../../c-api/memory.rst:755 +#: ../../c-api/memory.rst:761 +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:769 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:773 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..20db7621d 100644 --- a/c-api/memoryview.po +++ b/c-api/memoryview.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,6 +40,14 @@ msgstr "" #: ../../c-api/memoryview.rst:18 msgid "" +"This instance of :c:type:`PyTypeObject` represents the Python memoryview " +"type. This is the same object as :class:`memoryview` in the Python layer." +msgstr "" +"Esta instância de :c:type:`PyTypeObject` representa o tipo memoryview " +"Python. Este é o mesmo objeto que :class:`memoryview` na camada Python." + +#: ../../c-api/memoryview.rst:24 +msgid "" "Create a memoryview object from an object that provides the buffer " "interface. If *obj* supports writable buffer exports, the memoryview object " "will be read/write, otherwise it may be either read-only or read/write at " @@ -50,15 +58,15 @@ msgstr "" "memoryview será de leitura/gravação; caso contrário, poderá ser somente " "leitura ou leitura/gravação, a critério do exportador." -#: ../../c-api/memoryview.rst:26 +#: ../../c-api/memoryview.rst:32 msgid "Flag to request a readonly buffer." msgstr "Sinalizador para solicitar um buffer de somente leitura." -#: ../../c-api/memoryview.rst:31 +#: ../../c-api/memoryview.rst:37 msgid "Flag to request a writable buffer." msgstr "Sinalizador para solicitar um buffer gravável." -#: ../../c-api/memoryview.rst:36 +#: ../../c-api/memoryview.rst:42 msgid "" "Create a memoryview object using *mem* as the underlying buffer. *flags* can " "be one of :c:macro:`PyBUF_READ` or :c:macro:`PyBUF_WRITE`." @@ -66,7 +74,7 @@ msgstr "" "Cria um objeto memoryview usando *mem* como o buffer subjacente. *flags* " "pode ser um dos seguintes :c:macro:`PyBUF_READ` ou :c:macro:`PyBUF_WRITE`." -#: ../../c-api/memoryview.rst:43 +#: ../../c-api/memoryview.rst:49 msgid "" "Create a memoryview object wrapping the given buffer structure *view*. For " "simple byte buffers, :c:func:`PyMemoryView_FromMemory` is the preferred " @@ -76,7 +84,7 @@ msgstr "" "fornecida. Para buffers de bytes simples, :c:func:`PyMemoryView_FromMemory` " "é a função preferida." -#: ../../c-api/memoryview.rst:49 +#: ../../c-api/memoryview.rst:55 msgid "" "Create a memoryview object to a :term:`contiguous` chunk of memory (in " "either 'C' or 'F'ortran *order*) from an object that defines the buffer " @@ -90,14 +98,14 @@ msgstr "" "memoryview apontará para a memória original. Caso contrário, é feita uma " "cópia e a visualização da memória aponta para um novo objeto bytes." -#: ../../c-api/memoryview.rst:55 +#: ../../c-api/memoryview.rst:61 msgid "" "*buffertype* can be one of :c:macro:`PyBUF_READ` or :c:macro:`PyBUF_WRITE`." msgstr "" "*buffertype* pode ser um entre :c:macro:`PyBUF_READ` ou :c:macro:" "`PyBUF_WRITE`." -#: ../../c-api/memoryview.rst:60 +#: ../../c-api/memoryview.rst:66 msgid "" "Return true if the object *obj* is a memoryview object. It is not currently " "allowed to create subclasses of :class:`memoryview`. This function always " @@ -107,7 +115,7 @@ msgstr "" "permitido criar subclasses de :class:`memoryview`. Esta função sempre tem " "sucesso." -#: ../../c-api/memoryview.rst:67 +#: ../../c-api/memoryview.rst:73 msgid "" "Return a pointer to the memoryview's private copy of the exporter's buffer. " "*mview* **must** be a memoryview instance; this macro doesn't check its " @@ -117,7 +125,7 @@ msgstr "" "*mview* **deve** ser uma instância de memoryview; Se essa macro não " "verificar seu tipo, faça você mesmo ou corre o risco de travar." -#: ../../c-api/memoryview.rst:73 +#: ../../c-api/memoryview.rst:79 msgid "" "Return either a pointer to the exporting object that the memoryview is based " "on or ``NULL`` if the memoryview has been created by one of the functions :c:" diff --git a/c-api/method.po b/c-api/method.po index 98672273e..4cd4a050f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c9d99a642 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 +# python-doc bot, 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,10 +30,8 @@ msgstr "Objetos do Módulo" #: ../../c-api/module.rst:15 msgid "" "This instance of :c:type:`PyTypeObject` represents the Python module type. " -"This is exposed to Python programs as ``types.ModuleType``." +"This is exposed to Python programs as :py:class:`types.ModuleType`." msgstr "" -"Esta instância de :c:type:`PyTypeObject` representa o tipo de módulo Python. " -"Isso é exposto a programas Python como ``types.ModuleType``." #: ../../c-api/module.rst:21 msgid "" @@ -57,28 +51,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:286 +#: ../../c-api/module.rst:506 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 +84,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 +96,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 +106,23 @@ msgstr "" "``PyObject_*`` em vez de manipular diretamente o :attr:`~object.__dict__` de " "um módulo." -#: ../../c-api/module.rst:80 +#: ../../c-api/module.rst:74 +msgid "" +"The returned reference is borrowed from the module; it is valid until the " +"module is destroyed." +msgstr "" + +#: ../../c-api/module.rst:84 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:93 msgid "" "Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to " "``'utf-8'``." @@ -126,7 +130,14 @@ msgstr "" "Semelhante a :c:func:`PyModule_GetNameObject` mas retorna o nome codificado " "em ``'utf-8'``" -#: ../../c-api/module.rst:93 +#: ../../c-api/module.rst:96 +msgid "" +"The returned buffer is only valid until the module is renamed or destroyed. " +"Note that Python code may rename a module by setting its :py:attr:`~module." +"__name__` attribute." +msgstr "" + +#: ../../c-api/module.rst:102 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 +147,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:109 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 +155,26 @@ 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 "" +"On error, return ``NULL`` with an exception set. Use :c:func:" +"`PyErr_Occurred` to tell this case apart from a missing :c:type:`!" +"PyModuleDef`." +msgstr "" + +#: ../../c-api/module.rst:123 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:133 msgid "" "Similar to :c:func:`PyModule_GetFilenameObject` but return the filename " "encoded to 'utf-8'." @@ -164,7 +182,13 @@ 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:136 +msgid "" +"The returned buffer is only valid until the module's :py:attr:`~module." +"__file__` attribute is reassigned or the module is destroyed." +msgstr "" + +#: ../../c-api/module.rst:139 msgid "" ":c:func:`PyModule_GetFilename` raises :exc:`UnicodeEncodeError` on " "unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead." @@ -172,11 +196,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:147 msgid "Initializing C modules" msgstr "Inicializando módulos C" -#: ../../c-api/module.rst:133 +#: ../../c-api/module.rst:149 msgid "" "Modules objects are usually created from extension modules (shared libraries " "which export an initialization function), or compiled-in modules (where the " @@ -189,7 +213,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:154 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 +224,7 @@ msgstr "" "solicitar \"inicialização multifásica\" retornando a própria estrutura de " "definição." -#: ../../c-api/module.rst:144 +#: ../../c-api/module.rst:160 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 +234,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:166 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:170 msgid "Name for the new module." msgstr "Nome para o novo módulo." -#: ../../c-api/module.rst:158 +#: ../../c-api/module.rst:174 msgid "" "Docstring for the module; usually a docstring variable created with :c:macro:" "`PyDoc_STRVAR` is used." @@ -226,7 +250,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:179 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 +261,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:183 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 +271,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:187 msgid "" "Setting ``m_size`` to ``-1`` means that the module does not support sub-" "interpreters, because it has global state." @@ -255,7 +279,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:190 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 +291,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:195 msgid "See :PEP:`3121` for more details." msgstr "Ver :PEP:`3121` para mais detalhes." -#: ../../c-api/module.rst:183 +#: ../../c-api/module.rst:199 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 +304,7 @@ msgstr "" "valores :c:type:`PyMethodDef`. Pode ser ``NULL`` se nenhuma função estiver " "presente." -#: ../../c-api/module.rst:188 +#: ../../c-api/module.rst:204 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 +314,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:210 msgid "" "Prior to version 3.5, this member was always set to ``NULL``, and was " "defined as:" @@ -298,7 +322,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:217 msgid "" "A traversal function to call during GC traversal of the module object, or " "``NULL`` if not needed." @@ -306,8 +330,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:220 ../../c-api/module.rst:235 +#: ../../c-api/module.rst:256 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 +347,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:227 ../../c-api/module.rst:248 +#: ../../c-api/module.rst:263 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:232 msgid "" "A clear function to call during GC clearing of the module object, or " "``NULL`` if not needed." @@ -336,7 +360,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:242 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 +368,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:253 msgid "" "A function to call during deallocation of the module object, or ``NULL`` if " "not needed." @@ -353,11 +382,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:267 msgid "Single-phase initialization" msgstr "inicialização de fase única" -#: ../../c-api/module.rst:253 +#: ../../c-api/module.rst:269 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 +396,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:275 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:282 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:290 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,48 +421,73 @@ 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:293 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:299 msgid "Multi-phase initialization" msgstr "Inicialização multifásica" -#: ../../c-api/module.rst:285 +#: ../../c-api/module.rst:301 msgid "" "An alternate way to specify extensions is to request \"multi-phase " "initialization\". Extension modules created this way behave more like Python " "modules: the initialization is split between the *creation phase*, when the " "module object is created, and the *execution phase*, when it is populated. " -"The distinction is similar to the :py:meth:`!__new__` and :py:meth:`!" -"__init__` methods of classes." +"The distinction is similar to the :py:meth:`~object.__new__` and :py:meth:" +"`~object.__init__` methods of classes." msgstr "" -#: ../../c-api/module.rst:292 +#: ../../c-api/module.rst:308 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-" -"imported, a new module object is created, and the old module is subject to " -"normal garbage collection -- as with Python modules. By default, multiple " -"modules created from the same definition should be independent: changes to " -"one should not affect the others. This means that all state should be " -"specific to the module object (using e.g. using :c:func:" -"`PyModule_GetState`), or its contents (such as the module's :attr:`~object." -"__dict__` or individual classes created with :c:func:`PyType_FromSpec`)." +"not singletons. For example, if the :py:attr:`sys.modules` entry is removed " +"and the module is re-imported, a new module object is created, and typically " +"populated with fresh method and type objects. The old module is subject to " +"normal garbage collection. This mirrors the behavior of pure-Python modules." +msgstr "" + +#: ../../c-api/module.rst:316 +msgid "" +"Additional module instances may be created in :ref:`sub-interpreters ` or after after Python runtime reinitialization (:c:" +"func:`Py_Finalize` and :c:func:`Py_Initialize`). In these cases, sharing " +"Python objects between module instances would likely cause crashes or " +"undefined behavior." +msgstr "" + +#: ../../c-api/module.rst:323 +msgid "" +"To avoid such issues, each instance of an extension module should be " +"*isolated*: changes to one instance should not implicitly affect the others, " +"and all state, including references to Python objects, should be specific to " +"a particular module instance. See :ref:`isolating-extensions-howto` for more " +"details and a practical guide." msgstr "" -#: ../../c-api/module.rst:302 +#: ../../c-api/module.rst:329 +msgid "" +"A simpler way to avoid these issues is :ref:`raising an error on repeated " +"initialization `." +msgstr "" +"Uma maneira mais simples de evitar esses problemas é :ref:`levantar um erro " +"na inicialização repetida `." + +#: ../../c-api/module.rst:332 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." +"support :ref:`sub-interpreters `, or otherwise " +"explicitly signal a lack of support. This is usually achieved by isolation " +"or blocking repeated initialization, as above. A module may also be limited " +"to the main interpreter using the :c:data:`Py_mod_multiple_interpreters` " +"slot." msgstr "" -#: ../../c-api/module.rst:306 +#: ../../c-api/module.rst:340 msgid "" "To request multi-phase initialization, the initialization function " "(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty :" @@ -438,7 +495,7 @@ msgid "" "instance must be initialized with the following function:" msgstr "" -#: ../../c-api/module.rst:313 +#: ../../c-api/module.rst:347 msgid "" "Ensures a module definition is a properly initialized Python object that " "correctly reports its type and reference count." @@ -446,54 +503,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:350 msgid "Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred." msgstr "" -#: ../../c-api/module.rst:320 +#: ../../c-api/module.rst:354 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:361 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:365 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:369 msgid "The *m_slots* array must be terminated by a slot with id 0." msgstr "" -#: ../../c-api/module.rst:337 +#: ../../c-api/module.rst:371 msgid "The available slot types are:" msgstr "Os tipos de slot disponíveis são:" -#: ../../c-api/module.rst:341 +#: ../../c-api/module.rst:375 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:382 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:387 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:391 msgid "" "Multiple ``Py_mod_create`` slots may not be specified in one module " "definition." @@ -501,7 +558,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:394 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 +567,7 @@ msgid "" "through symlinks, all while sharing a single module definition." msgstr "" -#: ../../c-api/module.rst:366 +#: ../../c-api/module.rst:400 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 +577,7 @@ msgid "" "``Py_mod_create``." msgstr "" -#: ../../c-api/module.rst:375 +#: ../../c-api/module.rst:409 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 +585,7 @@ msgid "" "function is:" msgstr "" -#: ../../c-api/module.rst:384 +#: ../../c-api/module.rst:418 msgid "" "If multiple ``Py_mod_exec`` slots are specified, they are processed in the " "order they appear in the *m_slots* array." @@ -536,55 +593,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:423 ../../c-api/module.rst:456 msgid "Specifies one of the following values:" msgstr "" -#: ../../c-api/module.rst:395 +#: ../../c-api/module.rst:429 msgid "The module does not support being imported in subinterpreters." msgstr "" -#: ../../c-api/module.rst:399 +#: ../../c-api/module.rst:433 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:439 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:443 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:446 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:449 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:462 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:467 msgid "The module is safe to run without an active GIL." msgstr "" -#: ../../c-api/module.rst:433 +#: ../../c-api/module.rst:469 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 +649,27 @@ msgid "" "threaded-cpython` for more detail." msgstr "" -#: ../../c-api/module.rst:438 +#: ../../c-api/module.rst:474 msgid "" "Multiple ``Py_mod_gil`` slots may not be specified in one module definition." msgstr "" -#: ../../c-api/module.rst:440 +#: ../../c-api/module.rst:476 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:481 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:484 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:486 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 +677,14 @@ msgid "" "``PyModule_ExecDef`` must be called to fully initialize a module." msgstr "" -#: ../../c-api/module.rst:457 +#: ../../c-api/module.rst:493 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:501 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 +692,24 @@ msgid "" "emitted." msgstr "" -#: ../../c-api/module.rst:474 +#: ../../c-api/module.rst:510 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:517 msgid "Process any execution slots (:c:data:`Py_mod_exec`) given in *def*." msgstr "" -#: ../../c-api/module.rst:487 +#: ../../c-api/module.rst:523 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:532 msgid "" "Add the functions from the ``NULL`` terminated *functions* array to " "*module*. Refer to the :c:type:`PyMethodDef` documentation for details on " @@ -664,11 +721,17 @@ msgid "" "``PyModule_FromDefAndSpec``." msgstr "" -#: ../../c-api/module.rst:508 +#: ../../c-api/module.rst:541 +msgid "" +"The *functions* array must be statically allocated (or otherwise guaranteed " +"to outlive the module object)." +msgstr "" + +#: ../../c-api/module.rst:547 msgid "Support functions" msgstr "" -#: ../../c-api/module.rst:510 +#: ../../c-api/module.rst:549 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 +739,45 @@ msgid "" "module state:" msgstr "" -#: ../../c-api/module.rst:517 +#: ../../c-api/module.rst:556 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:559 msgid "" "On success, return ``0``. On error, raise an exception and return ``-1``." msgstr "" -#: ../../c-api/module.rst:522 +#: ../../c-api/module.rst:561 ../../c-api/module.rst:612 +#: ../../c-api/module.rst:639 +msgid "Example usage::" +msgstr "Exemplo de uso::" + +#: ../../c-api/module.rst:563 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:575 +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:579 msgid "" "The example can also be written without checking explicitly if *obj* is " "``NULL``::" @@ -706,13 +785,25 @@ msgstr "" "O exemplo também pode ser escrito sem verificar explicitamente se *obj* é " "``NULL``::" -#: ../../c-api/module.rst:551 +#: ../../c-api/module.rst:582 +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:591 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:594 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 +813,7 @@ msgid "" "internally to create a key object." msgstr "" -#: ../../c-api/module.rst:567 +#: ../../c-api/module.rst:607 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 +821,70 @@ msgid "" "variable." msgstr "" -#: ../../c-api/module.rst:583 +#: ../../c-api/module.rst:614 +msgid "" +"if (PyModule_Add(module, \"spam\", PyBytes_FromString(value)) < 0) {\n" +" goto error;\n" +"}" +msgstr "" + +#: ../../c-api/module.rst:623 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:626 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:633 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:636 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 +#: ../../c-api/module.rst:641 +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:654 msgid ":c:func:`PyModule_AddObject` is :term:`soft deprecated`." msgstr "" -#: ../../c-api/module.rst:619 +#: ../../c-api/module.rst:659 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:663 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:669 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 +892,14 @@ msgid "" "on success." msgstr "" -#: ../../c-api/module.rst:634 +#: ../../c-api/module.rst:674 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:681 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 +907,11 @@ msgid "" "with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:649 +#: ../../c-api/module.rst:689 msgid "Add a string constant to *module*." msgstr "" -#: ../../c-api/module.rst:653 +#: ../../c-api/module.rst:693 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 +919,7 @@ msgid "" "``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:663 +#: ../../c-api/module.rst:703 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 +930,25 @@ msgid "" "Return ``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: ../../c-api/module.rst:676 +#: ../../c-api/module.rst:716 msgid "Module lookup" msgstr "Pesquisa por módulos" -#: ../../c-api/module.rst:678 +#: ../../c-api/module.rst:718 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:722 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:727 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 +957,18 @@ msgid "" "to the interpreter state yet, it returns ``NULL``." msgstr "" -#: ../../c-api/module.rst:694 +#: ../../c-api/module.rst:734 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:737 msgid "Only effective on modules created using single-phase initialization." msgstr "" -#: ../../c-api/module.rst:699 +#: ../../c-api/module.rst:739 msgid "" "Python calls ``PyState_AddModule`` automatically after importing a module, " "so it is unnecessary (but harmless) to call it from module initialization " @@ -867,17 +979,17 @@ msgid "" "state updates)." msgstr "" -#: ../../c-api/module.rst:707 ../../c-api/module.rst:718 +#: ../../c-api/module.rst:747 ../../c-api/module.rst:758 msgid "The caller must hold the GIL." msgstr "" -#: ../../c-api/module.rst:709 +#: ../../c-api/module.rst:749 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:755 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 +1007,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:80 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:119 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:80 ../../c-api/module.rst:119 msgid "SystemError (built-in exception)" msgstr "" diff --git a/c-api/monitoring.po b/c-api/monitoring.po index ad91c273e..ae5c5c144 100644 --- a/c-api/monitoring.po +++ b/c-api/monitoring.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: -# Pedro Fonini, 2024 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +44,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 "" @@ -206,7 +207,160 @@ msgstr "Gerenciando o Estado de um Monitoramento" #: ../../c-api/monitoring.rst:133 msgid "" "Monitoring states can be managed with the help of monitoring scopes. A scope " -"would typically correspond to a python function." +"would typically correspond to a Python function." msgstr "" "Estados de monitoramento podem ser gerenciados com a ajuda de escopos de " -"monitoramento. Um escopo corresponderia tipicamente a um função python." +"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..429920d8f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..62e6079fe 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..ad42d98de 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 +# python-doc bot, 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -184,11 +180,8 @@ msgstr "" msgid "" "Flag to be used with multiple functions that print the object (like :c:func:" "`PyObject_Print` and :c:func:`PyFile_WriteObject`). If passed, these " -"function would use the :func:`str` of the object instead of the :func:`repr`." +"functions use the :func:`str` of the object instead of the :func:`repr`." msgstr "" -"Sinaliza a ser usado com múltiplas funções que imprimem o objeto (como :c:" -"func:`PyObject_Print` e :c:func:`PyFile_WriteObject`). Se passada, esta " -"função usaria o :func:`str` do objeto em vez do :func:`repr`." #: ../../c-api/object.rst:82 msgid "" @@ -221,19 +214,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 +236,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 +277,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 +294,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 +331,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 +343,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 +366,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 +381,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 +415,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 +449,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 +457,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 +466,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 +474,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 +483,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 +557,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 +582,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 +596,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 +605,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 +644,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 +652,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 +668,110 @@ 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 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:588 +msgid "" +"This function must only be called in a clear function of the type which has " +"the :c:macro:`Py_TPFLAGS_MANAGED_DICT` flag set." +msgstr "" + +#: ../../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..5841eab42 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..dda91fba9 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..dd950405d 100644 --- a/c-api/refcounting.po +++ b/c-api/refcounting.po @@ -1,42 +1,44 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/refcounting.rst:8 msgid "Reference Counting" -msgstr "Contagem de Referências" +msgstr "Contagem de referências" #: ../../c-api/refcounting.rst:10 msgid "" "The functions and macros in this section are used for managing reference " "counts of Python objects." msgstr "" +"As funções e macros nesta sessão são usadas para o gerenciamento de contagem " +"de referências de objetos Python." #: ../../c-api/refcounting.rst:16 msgid "Get the reference count of the Python object *o*." -msgstr "" +msgstr "Obtêm a contagem de referências do objeto Python *o*." #: ../../c-api/refcounting.rst:18 msgid "" @@ -48,14 +50,16 @@ msgid "" msgstr "" "Observe que o valor retornado pode não refletir realmente quantas " "referências ao objeto são realmente mantidas. Por exemplo, alguns objetos " -"são :term:`imortais ` e têm uma refcount muito alta que não reflete " -"o número real de referências. Consequentemente, não confie no valor " -"retornado para ser preciso, exceto um valor de 0 ou 1." +"são :term:`imortais ` e têm uma contagem de referências muito alta, " +"que não reflete o número real de referências. Consequentemente, não confie " +"no valor retornado para ser preciso, exceto um valor de 0 ou 1." #: ../../c-api/refcounting.rst:24 msgid "" "Use the :c:func:`Py_SET_REFCNT()` function to set an object reference count." msgstr "" +"Use a função :c:func:`Py_SET_REFCNT()` para definir uma contagem de " +"referências de um objeto." #: ../../c-api/refcounting.rst:26 msgid ":c:func:`Py_REFCNT()` is changed to the inline static function." @@ -81,12 +85,12 @@ msgstr "" #: ../../c-api/refcounting.rst:40 ../../c-api/refcounting.rst:53 #: ../../c-api/refcounting.rst:119 msgid "This function has no effect on :term:`immortal` objects." -msgstr "" +msgstr "Esta função não tem efeito sobre objetos :term:`imortais `." #: ../../c-api/refcounting.rst:44 ../../c-api/refcounting.rst:68 #: ../../c-api/refcounting.rst:147 msgid "Immortal objects are not modified." -msgstr "" +msgstr "Os objetos imortais não são modificados." #: ../../c-api/refcounting.rst:50 msgid "" @@ -100,6 +104,9 @@ msgid "" "term:`strong reference` in-place. The :c:func:`Py_NewRef` function can be " "used to create a new :term:`strong reference`." msgstr "" +"Esta função é geralmente usada para transformar uma :term:`referência " +"emprestada` em uma :term:`referência forte` local. A função :c:func:" +"`Py_NewRef` pode ser usada para criar uma nova :term:`referência forte`." #: ../../c-api/refcounting.rst:59 msgid "When done using the object, release is by calling :c:func:`Py_DECREF`." @@ -111,11 +118,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 @@ -123,10 +129,12 @@ msgid "" "Similar to :c:func:`Py_INCREF`, but the object *o* can be ``NULL``, in which " "case this has no effect." msgstr "" +"Semelhante a :c:func:`Py_INCREF`, mas o objeto *o* pode ser ``NULL``, caso " +"em que isso não tem efeito." #: ../../c-api/refcounting.rst:77 msgid "See also :c:func:`Py_XNewRef`." -msgstr "" +msgstr "Veja também :c:func:`Py_XNewRef`." #: ../../c-api/refcounting.rst:82 msgid "" @@ -150,21 +158,31 @@ 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 "" #: ../../c-api/refcounting.rst:107 msgid "Similar to :c:func:`Py_NewRef`, but the object *o* can be NULL." -msgstr "" +msgstr "Semelhante a :c:func:`Py_NewRef`, mas o objeto *o* pode ser NULL." #: ../../c-api/refcounting.rst:109 msgid "If the object *o* is ``NULL``, the function just returns ``NULL``." -msgstr "" +msgstr "Se o objeto *o* é ``NULL``, a função apenas retorna ``NULL``." #: ../../c-api/refcounting.rst:116 msgid "" @@ -191,6 +209,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,13 +280,23 @@ 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 " +"That arranges to set *dst* to *src* *before* releasing the reference to the " "old value of *dst*, so that any code triggered as a side-effect of *dst* " "getting torn down no longer believes *dst* points to a valid object." msgstr "" diff --git a/c-api/reflection.po b/c-api/reflection.po index 0d90700ee..8c2cce54e 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..1a146babd 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..6c7083d14 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..4d3dc355b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..72820cdea 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..576e1da69 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..976a79b9c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..f9daec1b5 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..183272d4a 100644 --- a/c-api/tuple.po +++ b/c-api/tuple.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +58,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`` 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`` 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 +99,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 +143,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 +151,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 +159,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 +169,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 +180,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 +206,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 +222,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 +232,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 +283,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 +317,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 +342,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..e1bae4247 100644 --- a/c-api/type.po +++ b/c-api/type.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Gustavo Reis, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Gustavo Reis, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +80,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 +108,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 +116,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 +146,42 @@ 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 "" +"Mark *type* as not watched. This undoes a previous call to :c:func:" +"`PyType_Watch`. *type* must not be ``NULL``." +msgstr "" + +#: ../../c-api/type.rst:124 +msgid "" +"An extension should never call this function with a *watcher_id* that was " +"not returned to it by a previous call to :c:func:`PyType_AddWatcher`." +msgstr "" + +#: ../../c-api/type.rst:127 +msgid "" +"On success, this function returns ``0``. On failure, this function returns " +"``-1`` with an exception set." +msgstr "" + +#: ../../c-api/type.rst:135 msgid "Type of a type-watcher callback function." msgstr "" -#: ../../c-api/type.rst:119 +#: ../../c-api/type.rst:137 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:146 msgid "" "Return non-zero if the type object *o* sets the feature *feature*. Type " "features are denoted by single bit flags." @@ -164,28 +189,38 @@ 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:152 +msgid "" +"Return non-zero if the type object *type* sets the subclass flag *flag*. " +"Subclass flags are denoted by :c:macro:`Py_TPFLAGS_*_SUBCLASS " +"`. This function is used by many ``_Check`` " +"functions for common types." +msgstr "" + +#: ../../c-api/type.rst:158 +msgid "" +":c:func:`PyObject_TypeCheck`, which is used as a slower alternative in " +"``_Check`` functions for types that don't come with subclass flags." +msgstr "" + +#: ../../c-api/type.rst:164 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:170 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:172 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:180 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 +230,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:187 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 +240,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:193 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 +252,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:199 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 +263,41 @@ msgid "" "handle." msgstr "" -#: ../../c-api/type.rst:177 +#: ../../c-api/type.rst:210 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 "" +"Retorna o nome do tipo. Equivalente a pegar o atributo :attr:`~type." +"__name__` do tipo." -#: ../../c-api/type.rst:183 +#: ../../c-api/type.rst:218 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 "" +"Retorna o nome qualificado do tipo. Equivalente a pegar o atributo :attr:" +"`~type.__qualname__` do tipo." -#: ../../c-api/type.rst:190 +#: ../../c-api/type.rst:225 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 "" +"Retorna o nome qualificado do tipo. Equivalente à ``f\"{type.__module__}." +"{type.__qualname__}\"``, ou :attr:`type.__qualname__` se :attr:`type." +"__module__` não é uma string ou é igual a ``\"builtins\"``." -#: ../../c-api/type.rst:198 +#: ../../c-api/type.rst:234 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 "" +"Retorna o nome do tipo do módulo. Equivalente a pegar o atributo :attr:`type." +"__module__`." -#: ../../c-api/type.rst:205 +#: ../../c-api/type.rst:242 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 +309,21 @@ 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:248 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:252 msgid "" ":c:func:`PyType_GetSlot` can now accept all types. Previously, it was " "limited to :ref:`heap types `." msgstr "" +":c:func:`PyType_GetSlot` agora aceita todos os tipos. Antes, estava limitada " +"a :ref:`tipos heap `." -#: ../../c-api/type.rst:221 +#: ../../c-api/type.rst:259 msgid "" "Return the module object associated with the given type when the type was " "created using :c:func:`PyType_FromModuleAndSpec`." @@ -285,7 +331,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:262 ../../c-api/type.rst:283 msgid "" "If no module is associated with the given type, sets :py:class:`TypeError` " "and returns ``NULL``." @@ -293,7 +339,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:265 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 +350,37 @@ msgid "" "type:`!PyCMethod` cannot be used." msgstr "" -#: ../../c-api/type.rst:240 +#: ../../c-api/type.rst:279 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:286 msgid "" "If the *type* has an associated module but its state is ``NULL``, returns " "``NULL`` without setting an exception." msgstr "" +"Se o *tipo* tem um módulo associado mas o seu estado é ``NULL``, retorna " +"``NULL`` sem definir uma exceção." -#: ../../c-api/type.rst:254 +#: ../../c-api/type.rst:294 msgid "" "Find the first superclass whose module was created from the given :c:type:" "`PyModuleDef` *def*, and return that module." msgstr "" +"Encontra a primeira super-classe da qual o módulo foi criado por :c:type:" +"`PyModuleDef` *def*, e retorna esse módulo." -#: ../../c-api/type.rst:257 +#: ../../c-api/type.rst:297 msgid "" "If no module is found, raises a :py:class:`TypeError` and returns ``NULL``." msgstr "" +"Se nenhum módulo é encontrado, levanta um :py:class:`TypeError` e retorna " +"``NULL``." -#: ../../c-api/type.rst:259 +#: ../../c-api/type.rst:299 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 +389,61 @@ msgid "" "type:`PyCMethod` calling convention." msgstr "" -#: ../../c-api/type.rst:269 +#: ../../c-api/type.rst:305 +msgid "" +"The returned reference is :term:`borrowed ` from *type*, " +"and will be valid as long as you hold a reference to *type*. Do not release " +"it with :c:func:`Py_DECREF` or similar." +msgstr "" + +#: ../../c-api/type.rst:314 msgid "Attempt to assign a version tag to the given type." msgstr "" -#: ../../c-api/type.rst:271 +#: ../../c-api/type.rst:316 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:324 +msgid "" +"Return true if instances of *type* support creating weak references, false " +"otherwise. This function always succeeds. *type* must not be ``NULL``." +msgstr "" + +#: ../../c-api/type.rst:328 +msgid ":ref:`weakrefobjects`" +msgstr "" + +#: ../../c-api/type.rst:329 +msgid ":py:mod:`weakref`" +msgstr "" + +#: ../../c-api/type.rst:333 msgid "Creating Heap-Allocated Types" msgstr "" -#: ../../c-api/type.rst:280 +#: ../../c-api/type.rst:335 msgid "" "The following functions and structs are used to create :ref:`heap types " "`." msgstr "" -#: ../../c-api/type.rst:285 +#: ../../c-api/type.rst:340 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:343 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:347 msgid "" "Metaclasses that override :c:member:`~PyTypeObject.tp_new` are not " "supported, except if ``tp_new`` is ``NULL``. (For backwards compatibility, " @@ -379,7 +452,7 @@ msgid "" "deprecated and in Python 3.14+ such metaclasses will not be supported.)" msgstr "" -#: ../../c-api/type.rst:299 +#: ../../c-api/type.rst:354 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 +461,7 @@ msgid "" "derives from :class:`object`." msgstr "" -#: ../../c-api/type.rst:305 +#: ../../c-api/type.rst:360 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 +470,11 @@ msgid "" "subclasses; it must be specified for each class individually." msgstr "" -#: ../../c-api/type.rst:312 +#: ../../c-api/type.rst:367 msgid "This function calls :c:func:`PyType_Ready` on the new type." msgstr "" -#: ../../c-api/type.rst:314 +#: ../../c-api/type.rst:369 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 +483,41 @@ msgid "" "Specifically:" msgstr "" -#: ../../c-api/type.rst:321 +#: ../../c-api/type.rst:376 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:378 msgid ":py:meth:`~object.__init__` is not called on the new class." msgstr "" -#: ../../c-api/type.rst:324 +#: ../../c-api/type.rst:379 msgid ":py:meth:`~object.__init_subclass__` is not called on any bases." msgstr "" -#: ../../c-api/type.rst:325 +#: ../../c-api/type.rst:380 msgid ":py:meth:`~object.__set_name__` is not called on new descriptors." msgstr "" -#: ../../c-api/type.rst:331 +#: ../../c-api/type.rst:387 msgid "Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``." msgstr "" -#: ../../c-api/type.rst:337 +#: ../../c-api/type.rst:393 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:398 ../../c-api/type.rst:416 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:401 ../../c-api/type.rst:419 ../../c-api/type.rst:436 msgid "" "The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*. which " "may result in incomplete initialization. Creating classes whose metaclass " @@ -452,60 +525,62 @@ msgid "" "it will be no longer allowed." msgstr "" -#: ../../c-api/type.rst:353 +#: ../../c-api/type.rst:410 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``." msgstr "" -#: ../../c-api/type.rst:370 +#: ../../c-api/type.rst:428 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``." msgstr "" -#: ../../c-api/type.rst:374 +#: ../../c-api/type.rst:432 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:453 msgid "Structure defining a type's behavior." msgstr "" -#: ../../c-api/type.rst:399 +#: ../../c-api/type.rst:457 msgid "Name of the type, used to set :c:member:`PyTypeObject.tp_name`." msgstr "" -#: ../../c-api/type.rst:403 +#: ../../c-api/type.rst:461 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:464 msgid "" "If zero, specifies that :c:member:`~PyTypeObject.tp_basicsize` should be " "inherited." msgstr "" -#: ../../c-api/type.rst:409 +#: ../../c-api/type.rst:467 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:477 msgid "Previously, this field could not be negative." msgstr "" -#: ../../c-api/type.rst:420 +#: ../../c-api/type.rst:481 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:485 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 +589,58 @@ msgid "" "only possible in the following situations:" msgstr "" -#: ../../c-api/type.rst:431 +#: ../../c-api/type.rst:492 msgid "" "The base is not variable-sized (its :c:member:`~PyTypeObject.tp_itemsize`)." msgstr "" -#: ../../c-api/type.rst:433 +#: ../../c-api/type.rst:494 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:496 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:499 msgid "With the :c:macro:`Py_TPFLAGS_ITEMS_AT_END` flag." msgstr "" -#: ../../c-api/type.rst:442 +#: ../../c-api/type.rst:503 msgid "Type flags, used to set :c:member:`PyTypeObject.tp_flags`." msgstr "" -#: ../../c-api/type.rst:444 +#: ../../c-api/type.rst:505 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:510 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:513 msgid "Each slot ID should be specified at most once." msgstr "" -#: ../../c-api/type.rst:462 +#: ../../c-api/type.rst:523 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:528 msgid "A slot ID." msgstr "" -#: ../../c-api/type.rst:469 +#: ../../c-api/type.rst:530 msgid "" "Slot IDs are named like the field names of the structures :c:type:" "`PyTypeObject`, :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, :c:" @@ -573,42 +648,42 @@ msgid "" "prefix. For example, use:" msgstr "" -#: ../../c-api/type.rst:475 +#: ../../c-api/type.rst:536 msgid "``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`" msgstr "" -#: ../../c-api/type.rst:476 +#: ../../c-api/type.rst:537 msgid "``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`" msgstr "" -#: ../../c-api/type.rst:477 +#: ../../c-api/type.rst:538 msgid "``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`" msgstr "" -#: ../../c-api/type.rst:479 +#: ../../c-api/type.rst:540 msgid "" "The following “offset” fields cannot be set using :c:type:`PyType_Slot`:" msgstr "" -#: ../../c-api/type.rst:481 +#: ../../c-api/type.rst:542 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:544 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:546 msgid "" ":c:member:`~PyTypeObject.tp_vectorcall_offset` (use " "``\"__vectorcalloffset__\"`` in :ref:`PyMemberDef `)" msgstr "" -#: ../../c-api/type.rst:489 +#: ../../c-api/type.rst:550 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 +691,48 @@ msgid "" "documentation ` for details." msgstr "" -#: ../../c-api/type.rst:495 +#: ../../c-api/type.rst:556 msgid "The following fields cannot be set at all when creating a heap type:" msgstr "" -#: ../../c-api/type.rst:497 +#: ../../c-api/type.rst:558 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:562 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:569 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:574 msgid "Slots in :c:type:`PyBufferProcs` may be set in the unlimited API." msgstr "" -#: ../../c-api/type.rst:517 +#: ../../c-api/type.rst:577 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:584 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:587 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..9a6a17c8b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..d9a44d2c1 100644 --- a/c-api/typeobj.po +++ b/c-api/typeobj.po @@ -1,37 +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: -# 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "Estruturas de objetos tipo" #: ../../c-api/typeobj.rst:8 msgid "" @@ -43,6 +38,13 @@ msgid "" "they are very important to the interpreter itself and to any extension " "module that implements new types." msgstr "" +"Talvez uma das estruturas mais importantes do sistema de objetos Python seja " +"a estrutura que define um novo tipo: a estrutura :c:type:`PyTypeObject`. " +"Objetos tipo podem ser manipulados usando qualquer uma das funções " +"``PyObject_*`` ou ``PyType_*``, mas não oferecem muito de interessante para " +"a maioria das aplicações Python. Esses objetos são fundamentais para o " +"comportamento dos objetos, portanto, são muito importantes para o próprio " +"interpretador e para qualquer módulo de extensão que implemente novos tipos." #: ../../c-api/typeobj.rst:16 msgid "" @@ -53,12 +55,12 @@ msgid "" "detail in this section. The fields will be described in the order in which " "they occur in the structure." msgstr "" -"Os objetos de tipo são bastante grandes em comparação com a maioria dos " -"tipos padrão. A razão para o tamanho é que cada objeto de tipo armazena um " -"grande número de valores, principalmente indicadores de função C, cada um " -"dos quais implementa uma pequena parte da funcionalidade do tipo. Os campos " -"do objeto de tipo são examinados em detalhes nesta seção. Os campos serão " -"descritos na ordem em que ocorrem na estrutura." +"Os objetos tipo são bastante grandes em comparação com a maioria dos tipos " +"padrão. A razão para o tamanho é que cada objeto de tipo armazena um grande " +"número de valores, principalmente indicadores de função C, cada um dos quais " +"implementa uma pequena parte da funcionalidade do tipo. Os campos do objeto " +"de tipo são examinados em detalhes nesta seção. Os campos serão descritos na " +"ordem em que ocorrem na estrutura." #: ../../c-api/typeobj.rst:23 msgid "" @@ -148,9 +150,9 @@ 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 "" +msgstr ":c:type:`Py_ssize_t`" #: ../../c-api/typeobj.rst:48 msgid ":c:member:`~PyTypeObject.tp_itemsize`" @@ -161,7 +163,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 +175,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 +194,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 +212,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 +227,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 +263,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 +276,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 +296,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 +304,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 +343,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 +352,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 +360,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`" @@ -367,13 +370,13 @@ msgstr "__lt__, __le__, __eq__, __ne__, __gt__, __ge__" #: ../../c-api/typeobj.rst:99 msgid "(:c:member:`~PyTypeObject.tp_weaklistoffset`)" -msgstr "" +msgstr "(:c:member:`~PyTypeObject.tp_weaklistoffset`)" #: ../../c-api/typeobj.rst:101 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 +388,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 +439,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 +459,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 +471,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`" @@ -478,13 +481,13 @@ msgstr "__set__, __delete__" #: ../../c-api/typeobj.rst:120 msgid "(:c:member:`~PyTypeObject.tp_dictoffset`)" -msgstr "" +msgstr "(:c:member:`~PyTypeObject.tp_dictoffset`)" #: ../../c-api/typeobj.rst:122 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 +499,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 +507,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 +519,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,9 +556,9 @@ 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 "" +msgstr "void *" #: ../../c-api/typeobj.rst:138 msgid "__subclasses__" @@ -595,7 +598,7 @@ msgstr ":c:type:`vectorcallfunc`" #: ../../c-api/typeobj.rst:150 msgid "[:c:member:`~PyTypeObject.tp_watched`]" -msgstr "" +msgstr "[:c:member:`~PyTypeObject.tp_watched`]" #: ../../c-api/typeobj.rst:150 msgid "unsigned char" @@ -605,6 +608,8 @@ msgstr "unsigned char" msgid "" "**()**: A slot name in parentheses indicates it is (effectively) deprecated." msgstr "" +"**()**: Um nome de slot entre parênteses indica que está (efetivamente) " +"descontinuado." #: ../../c-api/typeobj.rst:157 msgid "" @@ -637,10 +642,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 +692,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 +742,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 +1031,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 +1051,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 +1076,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 +1092,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 +1104,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 +1128,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 +1140,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 +1169,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 +1190,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 +1313,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 +1323,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:744 +#: ../../c-api/typeobj.rst:785 ../../c-api/typeobj.rst:804 +#: ../../c-api/typeobj.rst:823 ../../c-api/typeobj.rst:841 +#: ../../c-api/typeobj.rst:867 ../../c-api/typeobj.rst:884 +#: ../../c-api/typeobj.rst:896 ../../c-api/typeobj.rst:908 +#: ../../c-api/typeobj.rst:943 ../../c-api/typeobj.rst:967 +#: ../../c-api/typeobj.rst:989 ../../c-api/typeobj.rst:1012 +#: ../../c-api/typeobj.rst:1040 ../../c-api/typeobj.rst:1059 +#: ../../c-api/typeobj.rst:1075 ../../c-api/typeobj.rst:1114 +#: ../../c-api/typeobj.rst:1125 ../../c-api/typeobj.rst:1135 +#: ../../c-api/typeobj.rst:1145 ../../c-api/typeobj.rst:1159 +#: ../../c-api/typeobj.rst:1177 ../../c-api/typeobj.rst:1200 +#: ../../c-api/typeobj.rst:1218 ../../c-api/typeobj.rst:1231 +#: ../../c-api/typeobj.rst:1253 ../../c-api/typeobj.rst:1297 +#: ../../c-api/typeobj.rst:1318 ../../c-api/typeobj.rst:1337 +#: ../../c-api/typeobj.rst:1367 ../../c-api/typeobj.rst:1389 +#: ../../c-api/typeobj.rst:1417 ../../c-api/typeobj.rst:1504 +#: ../../c-api/typeobj.rst:1580 ../../c-api/typeobj.rst:1643 +#: ../../c-api/typeobj.rst:1679 ../../c-api/typeobj.rst:1706 +#: ../../c-api/typeobj.rst:1731 ../../c-api/typeobj.rst:1746 +#: ../../c-api/typeobj.rst:1763 ../../c-api/typeobj.rst:1779 +#: ../../c-api/typeobj.rst:1811 ../../c-api/typeobj.rst:1843 +#: ../../c-api/typeobj.rst:1871 ../../c-api/typeobj.rst:1891 +#: ../../c-api/typeobj.rst:1920 ../../c-api/typeobj.rst:1966 +#: ../../c-api/typeobj.rst:1985 ../../c-api/typeobj.rst:2028 +#: ../../c-api/typeobj.rst:2052 ../../c-api/typeobj.rst:2086 +#: ../../c-api/typeobj.rst:2116 ../../c-api/typeobj.rst:2129 +#: ../../c-api/typeobj.rst:2139 ../../c-api/typeobj.rst:2156 +#: ../../c-api/typeobj.rst:2173 ../../c-api/typeobj.rst:2189 +#: ../../c-api/typeobj.rst:2226 ../../c-api/typeobj.rst:2249 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 +1375,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 +1387,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:746 +#: ../../c-api/typeobj.rst:869 ../../c-api/typeobj.rst:969 +#: ../../c-api/typeobj.rst:991 ../../c-api/typeobj.rst:1708 +#: ../../c-api/typeobj.rst:1733 ../../c-api/typeobj.rst:1873 +#: ../../c-api/typeobj.rst:1893 ../../c-api/typeobj.rst:1968 +#: ../../c-api/typeobj.rst:2088 ../../c-api/typeobj.rst:2228 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 +1425,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 +1437,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:618 +#: ../../c-api/typeobj.rst:630 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 :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:625 +#: ../../c-api/typeobj.rst:634 msgid "" -"For any type with variable-length instances, this field must not be ``NULL``." +"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:629 +#: ../../c-api/typeobj.rst:640 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)." +"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:637 +#: ../../c-api/typeobj.rst:646 +msgid "" +"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: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:682 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 +1599,11 @@ msgid "" "The function signature is::" msgstr "" -#: ../../c-api/typeobj.rst:643 +#: ../../c-api/typeobj.rst:686 +msgid "void tp_dealloc(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:688 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 +1621,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:703 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:707 +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:715 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 +1645,51 @@ msgid "" "dangling pointers, the recommended way to achieve this is:" msgstr "" -#: ../../c-api/typeobj.rst:693 +#: ../../c-api/typeobj.rst:721 +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:732 +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:751 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:756 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:760 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:764 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 +1697,13 @@ msgid "" "`PyVectorcall_Call`." msgstr "" -#: ../../c-api/typeobj.rst:713 +#: ../../c-api/typeobj.rst:771 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:777 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 +1713,7 @@ msgid "" "`Py_TPFLAGS_HAVE_VECTORCALL` flag." msgstr "" -#: ../../c-api/typeobj.rst:729 +#: ../../c-api/typeobj.rst:787 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 +1721,11 @@ msgid "" "func:`PyVectorcall_Call` is explicitly called." msgstr "" -#: ../../c-api/typeobj.rst:738 +#: ../../c-api/typeobj.rst:798 msgid "An optional pointer to the get-attribute-string function." msgstr "" -#: ../../c-api/typeobj.rst:740 +#: ../../c-api/typeobj.rst:800 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 +1733,13 @@ msgid "" "attribute name." msgstr "" -#: ../../c-api/typeobj.rst:746 ../../c-api/typeobj.rst:942 +#: ../../c-api/typeobj.rst:806 ../../c-api/typeobj.rst:1014 msgid "" "Group: :c:member:`~PyTypeObject.tp_getattr`, :c:member:`~PyTypeObject." "tp_getattro`" msgstr "" -#: ../../c-api/typeobj.rst:748 +#: ../../c-api/typeobj.rst:808 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 +1748,12 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:755 ../../c-api/typeobj.rst:955 +#: ../../c-api/typeobj.rst:817 ../../c-api/typeobj.rst:1029 msgid "" "An optional pointer to the function for setting and deleting attributes." msgstr "" -#: ../../c-api/typeobj.rst:757 +#: ../../c-api/typeobj.rst:819 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 +1761,13 @@ msgid "" "attribute name." msgstr "" -#: ../../c-api/typeobj.rst:763 ../../c-api/typeobj.rst:968 +#: ../../c-api/typeobj.rst:825 ../../c-api/typeobj.rst:1042 msgid "" "Group: :c:member:`~PyTypeObject.tp_setattr`, :c:member:`~PyTypeObject." "tp_setattro`" msgstr "" -#: ../../c-api/typeobj.rst:765 +#: ../../c-api/typeobj.rst:827 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 +1776,38 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:772 +#: ../../c-api/typeobj.rst:834 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:838 msgid "Formerly known as ``tp_compare`` and ``tp_reserved``." msgstr "" -#: ../../c-api/typeobj.rst:781 +#: ../../c-api/typeobj.rst:843 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:853 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:856 msgid "The signature is the same as for :c:func:`PyObject_Repr`::" msgstr "" -#: ../../c-api/typeobj.rst:796 +#: ../../c-api/typeobj.rst:858 +msgid "PyObject *tp_repr(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:860 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 +1816,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:871 ../../c-api/typeobj.rst:952 +#: ../../c-api/typeobj.rst:993 ../../c-api/typeobj.rst:1020 +#: ../../c-api/typeobj.rst:1048 ../../c-api/typeobj.rst:1089 +#: ../../c-api/typeobj.rst:1652 ../../c-api/typeobj.rst:1686 +#: ../../c-api/typeobj.rst:1815 ../../c-api/typeobj.rst:1848 +#: ../../c-api/typeobj.rst:1927 ../../c-api/typeobj.rst:1970 +#: ../../c-api/typeobj.rst:1990 ../../c-api/typeobj.rst:2034 +#: ../../c-api/typeobj.rst:2057 ../../c-api/typeobj.rst:2090 msgid "**Default:**" msgstr "**Padrão:**" -#: ../../c-api/typeobj.rst:809 +#: ../../c-api/typeobj.rst:873 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:880 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:886 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:892 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:898 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:904 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:910 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:920 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:923 msgid "The signature is the same as for :c:func:`PyObject_Hash`::" msgstr "" -#: ../../c-api/typeobj.rst:861 +#: ../../c-api/typeobj.rst:925 +msgid "Py_hash_t tp_hash(PyObject *);" +msgstr "" + +#: ../../c-api/typeobj.rst:927 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:931 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 +1902,7 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: ../../c-api/typeobj.rst:869 +#: ../../c-api/typeobj.rst:935 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 +1913,13 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: ../../c-api/typeobj.rst:879 ../../c-api/typeobj.rst:1563 +#: ../../c-api/typeobj.rst:945 ../../c-api/typeobj.rst:1645 msgid "" "Group: :c:member:`~PyTypeObject.tp_hash`, :c:member:`~PyTypeObject." "tp_richcompare`" msgstr "" -#: ../../c-api/typeobj.rst:881 +#: ../../c-api/typeobj.rst:947 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_richcompare`: a subtype inherits both of :c:member:`~PyTypeObject." @@ -1696,18 +1928,22 @@ msgid "" "are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:888 +#: ../../c-api/typeobj.rst:954 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericHash`." msgstr "" -#: ../../c-api/typeobj.rst:893 +#: ../../c-api/typeobj.rst:961 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:965 +msgid "PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);" +msgstr "" + +#: ../../c-api/typeobj.rst:976 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 +1952,15 @@ msgid "" "this handler.)" msgstr "" -#: ../../c-api/typeobj.rst:911 +#: ../../c-api/typeobj.rst:981 msgid "The signature is the same as for :c:func:`PyObject_Str`::" msgstr "" -#: ../../c-api/typeobj.rst:915 +#: ../../c-api/typeobj.rst:983 +msgid "PyObject *tp_str(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:985 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 +1968,32 @@ msgid "" "function." msgstr "" -#: ../../c-api/typeobj.rst:925 +#: ../../c-api/typeobj.rst:995 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:1003 msgid "An optional pointer to the get-attribute function." msgstr "" -#: ../../c-api/typeobj.rst:933 +#: ../../c-api/typeobj.rst:1005 msgid "The signature is the same as for :c:func:`PyObject_GetAttr`::" msgstr "" -#: ../../c-api/typeobj.rst:937 +#: ../../c-api/typeobj.rst:1007 +msgid "PyObject *tp_getattro(PyObject *self, PyObject *attr);" +msgstr "" + +#: ../../c-api/typeobj.rst:1009 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:1016 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 +2002,19 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:950 +#: ../../c-api/typeobj.rst:1022 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:957 +#: ../../c-api/typeobj.rst:1031 msgid "The signature is the same as for :c:func:`PyObject_SetAttr`::" msgstr "" -#: ../../c-api/typeobj.rst:961 +#: ../../c-api/typeobj.rst:1033 +msgid "int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);" +msgstr "" + +#: ../../c-api/typeobj.rst:1035 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 +2022,7 @@ msgid "" "attributes." msgstr "" -#: ../../c-api/typeobj.rst:970 +#: ../../c-api/typeobj.rst:1044 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 +2031,24 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:976 +#: ../../c-api/typeobj.rst:1050 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:981 +#: ../../c-api/typeobj.rst:1055 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:1061 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:1067 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 +2060,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:1077 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 +2076,17 @@ msgid "" "*really* inherited individually?" msgstr "" -#: ../../c-api/typeobj.rst:1017 +#: ../../c-api/typeobj.rst:1091 msgid "" ":c:data:`PyBaseObject_Type` uses ``Py_TPFLAGS_DEFAULT | " "Py_TPFLAGS_BASETYPE``." msgstr "" -#: ../../c-api/typeobj.rst:1020 +#: ../../c-api/typeobj.rst:1094 msgid "**Bit Masks:**" msgstr "" -#: ../../c-api/typeobj.rst:1024 +#: ../../c-api/typeobj.rst:1098 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 +2095,7 @@ msgid "" "zero." msgstr "" -#: ../../c-api/typeobj.rst:1031 +#: ../../c-api/typeobj.rst:1105 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 +2108,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:1116 ../../c-api/typeobj.rst:1127 +#: ../../c-api/typeobj.rst:1137 ../../c-api/typeobj.rst:1147 +#: ../../c-api/typeobj.rst:1179 msgid "???" msgstr "???" -#: ../../c-api/typeobj.rst:1047 +#: ../../c-api/typeobj.rst:1121 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:1132 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:1142 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:1152 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 +2143,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:1161 ../../c-api/typeobj.rst:1506 +#: ../../c-api/typeobj.rst:1582 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:1163 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,198 +2160,200 @@ msgid "" "values." msgstr "" -#: ../../c-api/typeobj.rst:1099 +#: ../../c-api/typeobj.rst:1173 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:1184 msgid "This bit indicates that objects behave like unbound methods." msgstr "" -#: ../../c-api/typeobj.rst:1112 +#: ../../c-api/typeobj.rst:1186 msgid "If this flag is set for ``type(meth)``, then:" msgstr "" -#: ../../c-api/typeobj.rst:1114 +#: ../../c-api/typeobj.rst:1188 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:1191 msgid "" "``meth.__get__(None, cls)(*args, **kwds)`` must be equivalent to " "``meth(*args, **kwds)``." msgstr "" -#: ../../c-api/typeobj.rst:1120 +#: ../../c-api/typeobj.rst:1194 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:1202 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:1208 msgid "" -"This bit indicates that instances of the class have a ``__dict__`` " -"attribute, and that the space for the dictionary is managed by the VM." +"This bit indicates that instances of the class have a :attr:`~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:1211 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:1213 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:1220 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:1226 msgid "" "This bit indicates that instances of the class should be weakly " "referenceable." msgstr "" -#: ../../c-api/typeobj.rst:1159 +#: ../../c-api/typeobj.rst:1233 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:1239 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:1242 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:1247 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:1255 msgid "This flag is inherited." msgstr "" -#: ../../c-api/typeobj.rst:1195 +#: ../../c-api/typeobj.rst:1269 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 " -"are faster than a generic check, like :c:func:`PyObject_IsInstance`. Custom " -"types that inherit from built-ins should have their :c:member:`~PyTypeObject." -"tp_flags` set appropriately, or the code that interacts with such types will " -"behave differently depending on what kind of check is used." +"Functions such as :c:func:`PyLong_Check` will call :c:func:" +"`PyType_FastSubclass` with one of these flags to quickly determine if a type " +"is a subclass of a built-in type; such specific checks are faster than a " +"generic check, like :c:func:`PyObject_IsInstance`. Custom types that inherit " +"from built-ins should have their :c:member:`~PyTypeObject.tp_flags` set " +"appropriately, or the code that interacts with such types will behave " +"differently depending on what kind of check is used." msgstr "" -#: ../../c-api/typeobj.rst:1206 +#: ../../c-api/typeobj.rst:1280 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:1285 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:1293 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:1299 msgid "" "This bit is inherited if :c:member:`~PyTypeObject.tp_call` is also inherited." msgstr "" -#: ../../c-api/typeobj.rst:1232 +#: ../../c-api/typeobj.rst:1306 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:1309 msgid "This flag can now be inherited by mutable classes." msgstr "" -#: ../../c-api/typeobj.rst:1239 +#: ../../c-api/typeobj.rst:1313 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:1315 msgid "" ":c:func:`PyType_Ready` automatically applies this flag to :ref:`static types " "`." msgstr "" -#: ../../c-api/typeobj.rst:1246 +#: ../../c-api/typeobj.rst:1320 msgid "This flag is not inherited." msgstr "" -#: ../../c-api/typeobj.rst:1252 +#: ../../c-api/typeobj.rst:1326 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:1330 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:1333 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:1339 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:1346 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:1357 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 +2361,23 @@ msgid "" "unset when registering :class:`collections.abc.Sequence`." msgstr "" -#: ../../c-api/typeobj.rst:1290 ../../c-api/typeobj.rst:1312 +#: ../../c-api/typeobj.rst:1364 ../../c-api/typeobj.rst:1386 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:1369 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:1372 ../../c-api/typeobj.rst:1394 msgid ":pep:`634` -- Structural Pattern Matching: Specification" -msgstr "" +msgstr ":pep:`634` -- Structural Pattern Matching: Specification" -#: ../../c-api/typeobj.rst:1305 +#: ../../c-api/typeobj.rst:1379 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 +2385,53 @@ msgid "" "unset when registering :class:`collections.abc.Mapping`." msgstr "" -#: ../../c-api/typeobj.rst:1317 +#: ../../c-api/typeobj.rst:1391 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:1401 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:1405 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:1413 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:1419 msgid "This field is *not* inherited by subtypes." msgstr "" -#: ../../c-api/typeobj.rst:1348 +#: ../../c-api/typeobj.rst:1426 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:1429 +msgid "int tp_traverse(PyObject *self, visitproc visit, void *arg);" +msgstr "" + +#: ../../c-api/typeobj.rst:1431 ../../c-api/typeobj.rst:1577 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:1434 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 +2441,19 @@ msgid "" "`!_thread` extension module::" msgstr "" -#: ../../c-api/typeobj.rst:1371 +#: ../../c-api/typeobj.rst:1440 +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:1449 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 +2461,47 @@ msgid "" "part of a reference cycle." msgstr "" -#: ../../c-api/typeobj.rst:1375 +#: ../../c-api/typeobj.rst:1453 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:1457 msgid "" "Heap types (:c:macro:`Py_TPFLAGS_HEAPTYPE`) must visit their type with::" msgstr "" -#: ../../c-api/typeobj.rst:1383 +#: ../../c-api/typeobj.rst:1459 +msgid "Py_VISIT(Py_TYPE(self));" +msgstr "" + +#: ../../c-api/typeobj.rst:1461 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:1464 +msgid "" +"#if PY_VERSION_HEX >= 0x03090000\n" +" Py_VISIT(Py_TYPE(self));\n" +"#endif" +msgstr "" + +#: ../../c-api/typeobj.rst:1468 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:1472 +msgid "PyObject_VisitManagedDict((PyObject*)self, visit, arg);" +msgstr "" + +#: ../../c-api/typeobj.rst:1475 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 +2530,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:1499 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:1508 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 +2545,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:1518 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:1521 +msgid "int tp_clear(PyObject *);" +msgstr "" + +#: ../../c-api/typeobj.rst:1523 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 +2571,7 @@ msgid "" "good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: ../../c-api/typeobj.rst:1453 +#: ../../c-api/typeobj.rst:1533 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 +2579,20 @@ msgid "" "example::" msgstr "" -#: ../../c-api/typeobj.rst:1467 +#: ../../c-api/typeobj.rst:1537 +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:1547 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 +2607,18 @@ msgid "" "performs the operations in a safe order." msgstr "" -#: ../../c-api/typeobj.rst:1479 +#: ../../c-api/typeobj.rst:1559 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:" +"`~PyTypeObject.tp_flags` field, the clear function must call :c:func:" "`PyObject_ClearManagedDict` like this::" msgstr "" -#: ../../c-api/typeobj.rst:1485 +#: ../../c-api/typeobj.rst:1563 +msgid "PyObject_ClearManagedDict((PyObject*)self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1565 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 +2626,7 @@ msgid "" "is not involved and :c:member:`~PyTypeObject.tp_dealloc` is called directly." msgstr "" -#: ../../c-api/typeobj.rst:1491 +#: ../../c-api/typeobj.rst:1571 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 +2636,7 @@ msgid "" "invoke :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: ../../c-api/typeobj.rst:1504 +#: ../../c-api/typeobj.rst:1584 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 +2644,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:1594 msgid "" "An optional pointer to the rich comparison function, whose signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1516 +#: ../../c-api/typeobj.rst:1596 +msgid "PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);" +msgstr "" + +#: ../../c-api/typeobj.rst:1598 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:1601 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 +2667,50 @@ msgid "" "set an exception condition." msgstr "" -#: ../../c-api/typeobj.rst:1524 +#: ../../c-api/typeobj.rst:1606 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:1612 msgid "Constant" msgstr "Constante" -#: ../../c-api/typeobj.rst:1530 +#: ../../c-api/typeobj.rst:1612 msgid "Comparison" msgstr "Comparação" -#: ../../c-api/typeobj.rst:1532 +#: ../../c-api/typeobj.rst:1614 msgid "``<``" msgstr "``<``" -#: ../../c-api/typeobj.rst:1534 +#: ../../c-api/typeobj.rst:1616 msgid "``<=``" msgstr "``<=``" -#: ../../c-api/typeobj.rst:1536 +#: ../../c-api/typeobj.rst:1618 msgid "``==``" msgstr "``==``" -#: ../../c-api/typeobj.rst:1538 +#: ../../c-api/typeobj.rst:1620 msgid "``!=``" msgstr "``!=``" -#: ../../c-api/typeobj.rst:1540 +#: ../../c-api/typeobj.rst:1622 msgid "``>``" msgstr "``>``" -#: ../../c-api/typeobj.rst:1542 +#: ../../c-api/typeobj.rst:1624 msgid "``>=``" msgstr "``>=``" -#: ../../c-api/typeobj.rst:1545 +#: ../../c-api/typeobj.rst:1627 msgid "" "The following macro is defined to ease writing rich comparison functions:" msgstr "" -#: ../../c-api/typeobj.rst:1549 +#: ../../c-api/typeobj.rst:1631 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 +2718,15 @@ msgid "" "specifies the requested operation, as for :c:func:`PyObject_RichCompare`." msgstr "" -#: ../../c-api/typeobj.rst:1555 +#: ../../c-api/typeobj.rst:1637 msgid "The returned value is a new :term:`strong reference`." msgstr "" -#: ../../c-api/typeobj.rst:1557 +#: ../../c-api/typeobj.rst:1639 msgid "On error, sets an exception and returns ``NULL`` from the function." msgstr "" -#: ../../c-api/typeobj.rst:1565 +#: ../../c-api/typeobj.rst:1647 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 +2734,7 @@ msgid "" "tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:1572 +#: ../../c-api/typeobj.rst:1654 msgid "" ":c:data:`PyBaseObject_Type` provides a :c:member:`~PyTypeObject." "tp_richcompare` implementation, which may be inherited. However, if only :c:" @@ -2437,13 +2743,13 @@ msgid "" "comparisons." msgstr "" -#: ../../c-api/typeobj.rst:1581 +#: ../../c-api/typeobj.rst:1663 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:1666 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 +2759,19 @@ msgid "" "`PyObject*` which is initialized to ``NULL``." msgstr "" -#: ../../c-api/typeobj.rst:1591 +#: ../../c-api/typeobj.rst:1673 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:1676 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:1681 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 +2780,7 @@ msgid "" "not be a problem." msgstr "" -#: ../../c-api/typeobj.rst:1606 +#: ../../c-api/typeobj.rst:1688 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 +2788,32 @@ msgid "" "unsafe to use this field." msgstr "" -#: ../../c-api/typeobj.rst:1614 +#: ../../c-api/typeobj.rst:1698 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:1702 msgid "This function has the same signature as :c:func:`PyObject_GetIter`::" msgstr "" -#: ../../c-api/typeobj.rst:1629 +#: ../../c-api/typeobj.rst:1704 +msgid "PyObject *tp_iter(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1715 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:1718 +msgid "PyObject *tp_iternext(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:1720 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 +2821,74 @@ msgid "" "this type are iterators." msgstr "" -#: ../../c-api/typeobj.rst:1639 +#: ../../c-api/typeobj.rst:1725 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:1729 msgid "This function has the same signature as :c:func:`PyIter_Next`." msgstr "" -#: ../../c-api/typeobj.rst:1652 +#: ../../c-api/typeobj.rst:1740 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:1743 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:1748 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:1756 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:1760 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:1765 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:1773 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:1776 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:1781 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:1789 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 +2896,7 @@ msgid "" "metatype." msgstr "" -#: ../../c-api/typeobj.rst:1703 +#: ../../c-api/typeobj.rst:1797 msgid "" "Slot initialization is subject to the rules of initializing globals. C99 " "requires the initializers to be \"address constants\". Function designators " @@ -2590,7 +2904,7 @@ msgid "" "valid C99 address constants." msgstr "" -#: ../../c-api/typeobj.rst:1708 +#: ../../c-api/typeobj.rst:1802 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 +2912,27 @@ msgid "" "strictly standard conforming in this particular behavior." msgstr "" -#: ../../c-api/typeobj.rst:1714 +#: ../../c-api/typeobj.rst:1808 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:1813 msgid "This field is not inherited by subtypes (obviously)." msgstr "" -#: ../../c-api/typeobj.rst:1723 +#: ../../c-api/typeobj.rst:1817 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:1823 msgid "The type's dictionary is stored here by :c:func:`PyType_Ready`." msgstr "" -#: ../../c-api/typeobj.rst:1731 +#: ../../c-api/typeobj.rst:1825 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 +2943,72 @@ msgid "" "be treated as read-only." msgstr "" -#: ../../c-api/typeobj.rst:1739 +#: ../../c-api/typeobj.rst:1833 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:1839 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:1845 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:1850 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:1855 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:1863 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:1865 ../../c-api/typeobj.rst:1883 +#: ../../c-api/typeobj.rst:1949 ../../c-api/typeobj.rst:1981 +#: ../../c-api/typeobj.rst:2007 msgid "The function signature is::" msgstr "A assinatura da função é::" -#: ../../c-api/typeobj.rst:1782 +#: ../../c-api/typeobj.rst:1867 +msgid "PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);" +msgstr "" + +#: ../../c-api/typeobj.rst:1880 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:1885 +msgid "int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);" +msgstr "" + +#: ../../c-api/typeobj.rst:1887 msgid "The *value* argument is set to ``NULL`` to delete the value." msgstr "" -#: ../../c-api/typeobj.rst:1800 +#: ../../c-api/typeobj.rst:1898 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:1901 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 +3016,19 @@ msgid "" "func:`PyObject_GenericGetAttr`." msgstr "" -#: ../../c-api/typeobj.rst:1808 +#: ../../c-api/typeobj.rst:1906 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:1909 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:1911 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 +3037,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:1917 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:1922 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 +3051,25 @@ msgid "" "`Py_TPFLAGS_MANAGED_DICT`." msgstr "" -#: ../../c-api/typeobj.rst:1831 +#: ../../c-api/typeobj.rst:1929 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:1932 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:1942 msgid "An optional pointer to an instance initialization function." msgstr "" -#: ../../c-api/typeobj.rst:1844 +#: ../../c-api/typeobj.rst:1944 msgid "" "This function corresponds to the :meth:`~object.__init__` method of " "classes. Like :meth:`!__init__`, it is possible to create an instance " @@ -2755,14 +3077,18 @@ msgid "" "instance by calling its :meth:`!__init__` method again." msgstr "" -#: ../../c-api/typeobj.rst:1853 +#: ../../c-api/typeobj.rst:1951 +msgid "int tp_init(PyObject *self, PyObject *args, PyObject *kwds);" +msgstr "" + +#: ../../c-api/typeobj.rst:1953 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:1957 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 +3100,52 @@ msgid "" "subtype's :c:member:`~PyTypeObject.tp_init` is called." msgstr "" -#: ../../c-api/typeobj.rst:1864 +#: ../../c-api/typeobj.rst:1964 msgid "Returns ``0`` on success, ``-1`` and sets an exception on error." msgstr "" -#: ../../c-api/typeobj.rst:1872 +#: ../../c-api/typeobj.rst:1972 msgid "" "For :ref:`static types ` this field does not have a default." msgstr "" -#: ../../c-api/typeobj.rst:1877 +#: ../../c-api/typeobj.rst:1979 msgid "An optional pointer to an instance allocation function." msgstr "" -#: ../../c-api/typeobj.rst:1885 +#: ../../c-api/typeobj.rst:1983 +msgid "PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);" +msgstr "" + +#: ../../c-api/typeobj.rst:1987 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:1992 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:1996 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:2005 msgid "An optional pointer to an instance creation function." msgstr "" -#: ../../c-api/typeobj.rst:1907 +#: ../../c-api/typeobj.rst:2009 +msgid "" +"PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);" +msgstr "" + +#: ../../c-api/typeobj.rst:2011 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 +3154,7 @@ msgid "" "that type (but not an unrelated type)." msgstr "" -#: ../../c-api/typeobj.rst:1913 +#: ../../c-api/typeobj.rst:2017 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 +3166,20 @@ msgid "" "be deferred to :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: ../../c-api/typeobj.rst:1921 +#: ../../c-api/typeobj.rst:2025 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:2030 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:2036 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 +3187,44 @@ msgid "" "factory function." msgstr "" -#: ../../c-api/typeobj.rst:1940 +#: ../../c-api/typeobj.rst:2046 msgid "" "An optional pointer to an instance deallocation function. Its signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1944 +#: ../../c-api/typeobj.rst:2048 +msgid "void tp_free(void *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2050 msgid "" "An initializer that is compatible with this signature is :c:func:" "`PyObject_Free`." msgstr "" -#: ../../c-api/typeobj.rst:1948 +#: ../../c-api/typeobj.rst:2054 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:2059 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:2063 msgid "" "For static subtypes, :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_Del`." msgstr "" -#: ../../c-api/typeobj.rst:1962 +#: ../../c-api/typeobj.rst:2070 msgid "An optional pointer to a function called by the garbage collector." msgstr "" -#: ../../c-api/typeobj.rst:1964 +#: ../../c-api/typeobj.rst:2072 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 +3236,93 @@ msgid "" "instance. The signature is::" msgstr "" -#: ../../c-api/typeobj.rst:1974 +#: ../../c-api/typeobj.rst:2080 +msgid "int tp_is_gc(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2082 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:2092 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:2100 msgid "Tuple of base types." msgstr "" -#: ../../c-api/typeobj.rst:1992 ../../c-api/typeobj.rst:2016 +#: ../../c-api/typeobj.rst:2102 ../../c-api/typeobj.rst:2126 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:2105 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:2112 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:2118 ../../c-api/typeobj.rst:2141 +#: ../../c-api/typeobj.rst:2158 ../../c-api/typeobj.rst:2175 +#: ../../c-api/typeobj.rst:2191 msgid "This field is not inherited." msgstr "" -#: ../../c-api/typeobj.rst:2013 +#: ../../c-api/typeobj.rst:2123 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:2131 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:2137 msgid "Unused. Internal use only." msgstr "" -#: ../../c-api/typeobj.rst:2036 +#: ../../c-api/typeobj.rst:2146 msgid "" "A collection of subclasses. Internal use only. May be an invalid pointer." msgstr "" -#: ../../c-api/typeobj.rst:2038 +#: ../../c-api/typeobj.rst:2148 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:2153 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:2163 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:2168 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 +3330,27 @@ msgid "" "``_PyObject_GET_WEAKREFS_LISTPTR()`` macro to avoid the distinction." msgstr "" -#: ../../c-api/typeobj.rst:2070 +#: ../../c-api/typeobj.rst:2182 msgid "" "This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead." msgstr "" -#: ../../c-api/typeobj.rst:2075 +#: ../../c-api/typeobj.rst:2187 msgid "Used to index into the method cache. Internal use only." msgstr "" -#: ../../c-api/typeobj.rst:2084 +#: ../../c-api/typeobj.rst:2198 msgid "" -"An optional pointer to an instance finalization function. Its signature is::" +"An optional pointer to an instance finalization function. This is the C " +"implementation of the :meth:`~object.__del__` special method. Its signature " +"is::" +msgstr "" + +#: ../../c-api/typeobj.rst:2202 +msgid "void tp_finalize(PyObject *self);" msgstr "" -#: ../../c-api/typeobj.rst:2088 +#: ../../c-api/typeobj.rst:2204 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 +3360,40 @@ msgid "" "object in a sane state." msgstr "" -#: ../../c-api/typeobj.rst:2095 +#: ../../c-api/typeobj.rst:2211 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:2214 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:2234 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:2238 msgid "\"Safe object finalization\" (:pep:`442`)" msgstr "\"Finalização segura de objetos\" (:pep:`442`)" -#: ../../c-api/typeobj.rst:2140 +#: ../../c-api/typeobj.rst:2243 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 +3401,65 @@ msgid "" "meth:`~object.__new__` and :meth:`~object.__init__` is used." msgstr "" -#: ../../c-api/typeobj.rst:2148 +#: ../../c-api/typeobj.rst:2251 msgid "This field is never inherited." msgstr "" -#: ../../c-api/typeobj.rst:2150 +#: ../../c-api/typeobj.rst:2253 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:2258 msgid "Internal. Do not use." msgstr "" -#: ../../c-api/typeobj.rst:2163 +#: ../../c-api/typeobj.rst:2266 msgid "Static Types" msgstr "" -#: ../../c-api/typeobj.rst:2165 +#: ../../c-api/typeobj.rst:2268 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:2272 msgid "" "This results in types that are limited relative to types defined in Python:" msgstr "" -#: ../../c-api/typeobj.rst:2171 +#: ../../c-api/typeobj.rst:2274 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:2276 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:2278 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:2282 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:2290 msgid "Heap Types" msgstr "Tipos no heap" -#: ../../c-api/typeobj.rst:2189 +#: ../../c-api/typeobj.rst:2292 msgid "" "An alternative to :ref:`static types ` is *heap-allocated " "types*, or *heap types* for short, which correspond closely to classes " @@ -3116,29 +3467,75 @@ msgid "" "`Py_TPFLAGS_HEAPTYPE` flag set." msgstr "" -#: ../../c-api/typeobj.rst:2194 +#: ../../c-api/typeobj.rst:2297 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:2305 msgid "Number Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2209 +#: ../../c-api/typeobj.rst:2312 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:2318 ../../c-api/typeobj.rst:2774 msgid "Here is the structure definition::" msgstr "" -#: ../../c-api/typeobj.rst:2262 +#: ../../c-api/typeobj.rst:2320 +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:2365 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 +3545,31 @@ msgid "" "and set an exception." msgstr "" -#: ../../c-api/typeobj.rst:2271 +#: ../../c-api/typeobj.rst:2374 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:2525 msgid "Mapping Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2323 +#: ../../c-api/typeobj.rst:2532 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:2539 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:2547 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 +3577,7 @@ msgid "" "`PyMapping_Check` function to return ``1``, it can be ``NULL`` otherwise." msgstr "" -#: ../../c-api/typeobj.rst:2342 +#: ../../c-api/typeobj.rst:2557 msgid "" "This function is used by :c:func:`PyObject_SetItem`, :c:func:" "`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and :c:func:" @@ -3190,17 +3587,17 @@ msgid "" "deletion." msgstr "" -#: ../../c-api/typeobj.rst:2353 +#: ../../c-api/typeobj.rst:2568 msgid "Sequence Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2360 +#: ../../c-api/typeobj.rst:2575 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:2582 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 +3605,21 @@ msgid "" "member:`~PySequenceMethods.sq_ass_item` slots." msgstr "" -#: ../../c-api/typeobj.rst:2372 +#: ../../c-api/typeobj.rst:2591 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:2599 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:2607 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 +3628,7 @@ msgid "" "``1``, it can be ``NULL`` otherwise." msgstr "" -#: ../../c-api/typeobj.rst:2390 +#: ../../c-api/typeobj.rst:2613 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 +3637,7 @@ msgid "" "index is passed as is to the function." msgstr "" -#: ../../c-api/typeobj.rst:2397 +#: ../../c-api/typeobj.rst:2622 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 +3646,14 @@ msgid "" "``NULL`` if the object does not support item assignment and deletion." msgstr "" -#: ../../c-api/typeobj.rst:2406 +#: ../../c-api/typeobj.rst:2633 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:2642 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 +3663,7 @@ msgid "" "c:member:`~PyNumberMethods.nb_inplace_add` slot." msgstr "" -#: ../../c-api/typeobj.rst:2422 +#: ../../c-api/typeobj.rst:2653 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 +3673,76 @@ msgid "" "via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot." msgstr "" -#: ../../c-api/typeobj.rst:2433 +#: ../../c-api/typeobj.rst:2664 msgid "Buffer Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2441 +#: ../../c-api/typeobj.rst:2672 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:2680 ../../c-api/typeobj.rst:2731 +#: ../../c-api/typeobj.rst:2787 ../../c-api/typeobj.rst:2800 +#: ../../c-api/typeobj.rst:2814 ../../c-api/typeobj.rst:2826 msgid "The signature of this function is::" msgstr "" -#: ../../c-api/typeobj.rst:2451 +#: ../../c-api/typeobj.rst:2682 +msgid "int (PyObject *exporter, Py_buffer *view, int flags);" +msgstr "" + +#: ../../c-api/typeobj.rst:2684 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:2688 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:2691 msgid "Fill in the requested fields." msgstr "" -#: ../../c-api/typeobj.rst:2460 +#: ../../c-api/typeobj.rst:2693 msgid "Increment an internal counter for the number of exports." msgstr "" -#: ../../c-api/typeobj.rst:2462 +#: ../../c-api/typeobj.rst:2695 msgid "" "Set :c:expr:`view->obj` to *exporter* and increment :c:expr:`view->obj`." msgstr "" -#: ../../c-api/typeobj.rst:2464 +#: ../../c-api/typeobj.rst:2697 msgid "Return ``0``." msgstr "Retorna ``0``." -#: ../../c-api/typeobj.rst:2466 +#: ../../c-api/typeobj.rst:2699 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:2702 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:2705 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:2709 msgid "" "The individual fields of *view* are described in section :ref:`Buffer " "structure `, the rules how an exporter must react to " @@ -3349,7 +3750,7 @@ msgid "" "types>`." msgstr "" -#: ../../c-api/typeobj.rst:2481 +#: ../../c-api/typeobj.rst:2714 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 +3759,23 @@ msgid "" "internal` are read-only for the consumer." msgstr "" -#: ../../c-api/typeobj.rst:2488 +#: ../../c-api/typeobj.rst:2721 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:2724 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:2733 +msgid "void (PyObject *exporter, Py_buffer *view);" +msgstr "" + +#: ../../c-api/typeobj.rst:2735 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 +3783,15 @@ msgid "" "these optional steps:" msgstr "" -#: ../../c-api/typeobj.rst:2505 +#: ../../c-api/typeobj.rst:2740 msgid "Decrement an internal counter for the number of exports." msgstr "" -#: ../../c-api/typeobj.rst:2507 +#: ../../c-api/typeobj.rst:2742 msgid "If the counter is ``0``, free all memory associated with *view*." msgstr "" -#: ../../c-api/typeobj.rst:2509 +#: ../../c-api/typeobj.rst:2744 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 +3799,94 @@ msgid "" "*view* argument." msgstr "" -#: ../../c-api/typeobj.rst:2515 +#: ../../c-api/typeobj.rst:2750 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:2755 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:2763 msgid "Async Object Structures" msgstr "" -#: ../../c-api/typeobj.rst:2536 +#: ../../c-api/typeobj.rst:2771 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:2776 +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:2789 +msgid "PyObject *am_await(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2791 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:2794 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:2802 +msgid "PyObject *am_aiter(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2804 msgid "" "Must return an :term:`asynchronous iterator` object. See :meth:`~object." "__anext__` for details." msgstr "" -#: ../../c-api/typeobj.rst:2568 +#: ../../c-api/typeobj.rst:2807 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:2816 +msgid "PyObject *am_anext(PyObject *self);" +msgstr "" + +#: ../../c-api/typeobj.rst:2818 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:2828 +msgid "PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);" +msgstr "" + +#: ../../c-api/typeobj.rst:2830 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:2839 msgid "Slot Type typedefs" msgstr "" -#: ../../c-api/typeobj.rst:2600 +#: ../../c-api/typeobj.rst:2843 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 +3900,80 @@ msgid "" "length of the block should be :c:member:`~PyTypeObject.tp_basicsize`." msgstr "" -#: ../../c-api/typeobj.rst:2610 +#: ../../c-api/typeobj.rst:2853 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:2860 msgid "See :c:member:`~PyTypeObject.tp_free`." msgstr "" -#: ../../c-api/typeobj.rst:2621 +#: ../../c-api/typeobj.rst:2864 msgid "See :c:member:`~PyTypeObject.tp_new`." msgstr "" -#: ../../c-api/typeobj.rst:2625 +#: ../../c-api/typeobj.rst:2868 msgid "See :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: ../../c-api/typeobj.rst:2629 +#: ../../c-api/typeobj.rst:2872 msgid "See :c:member:`~PyTypeObject.tp_repr`." msgstr "" -#: ../../c-api/typeobj.rst:2633 ../../c-api/typeobj.rst:2642 +#: ../../c-api/typeobj.rst:2876 ../../c-api/typeobj.rst:2885 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:2880 ../../c-api/typeobj.rst:2891 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:2887 msgid "See :c:member:`~PyTypeObject.tp_getattro`." msgstr "" -#: ../../c-api/typeobj.rst:2651 +#: ../../c-api/typeobj.rst:2894 msgid "See :c:member:`~PyTypeObject.tp_setattro`." msgstr "" -#: ../../c-api/typeobj.rst:2655 +#: ../../c-api/typeobj.rst:2898 msgid "See :c:member:`~PyTypeObject.tp_descr_get`." msgstr "" -#: ../../c-api/typeobj.rst:2659 +#: ../../c-api/typeobj.rst:2902 msgid "See :c:member:`~PyTypeObject.tp_descr_set`." msgstr "" -#: ../../c-api/typeobj.rst:2663 +#: ../../c-api/typeobj.rst:2906 msgid "See :c:member:`~PyTypeObject.tp_hash`." msgstr "" -#: ../../c-api/typeobj.rst:2667 +#: ../../c-api/typeobj.rst:2910 msgid "See :c:member:`~PyTypeObject.tp_richcompare`." msgstr "" -#: ../../c-api/typeobj.rst:2671 +#: ../../c-api/typeobj.rst:2914 msgid "See :c:member:`~PyTypeObject.tp_iter`." msgstr "" -#: ../../c-api/typeobj.rst:2675 +#: ../../c-api/typeobj.rst:2918 msgid "See :c:member:`~PyTypeObject.tp_iternext`." msgstr "" -#: ../../c-api/typeobj.rst:2689 +#: ../../c-api/typeobj.rst:2932 msgid "See :c:member:`~PyAsyncMethods.am_send`." msgstr "" -#: ../../c-api/typeobj.rst:2705 +#: ../../c-api/typeobj.rst:2948 msgid "Examples" msgstr "Exemplos" -#: ../../c-api/typeobj.rst:2707 +#: ../../c-api/typeobj.rst:2950 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 +3981,179 @@ msgid "" "and :ref:`new-types-topics`." msgstr "" -#: ../../c-api/typeobj.rst:2712 +#: ../../c-api/typeobj.rst:2955 msgid "A basic :ref:`static type `::" msgstr "" -#: ../../c-api/typeobj.rst:2729 +#: ../../c-api/typeobj.rst:2957 +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:2972 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:2975 +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:3016 msgid "A type that supports weakrefs, instance dicts, and hashing::" msgstr "" -#: ../../c-api/typeobj.rst:2798 +#: ../../c-api/typeobj.rst:3018 +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:3041 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:3045 +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:3060 msgid "" "The simplest :ref:`static type ` with fixed-length instances::" msgstr "" -#: ../../c-api/typeobj.rst:2828 +#: ../../c-api/typeobj.rst:3062 +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:3071 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:3073 +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:851 ../../c-api/typeobj.rst:918 msgid "built-in function" msgstr "função embutida" -#: ../../c-api/typeobj.rst:787 +#: ../../c-api/typeobj.rst:851 msgid "repr" msgstr "repr" -#: ../../c-api/typeobj.rst:852 +#: ../../c-api/typeobj.rst:918 msgid "hash" msgstr "hash" diff --git a/c-api/unicode.po b/c-api/unicode.po index 0c979fa43..f1b8782a1 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 +# python-doc bot, 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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:75 +#: ../../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: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,227 @@ 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. " +"Return the high UTF-16 surrogate (``0xD800`` to ``0xDBFF``) for a Unicode " +"code point in the range ``[0x10000; 0x10FFFF]``." +msgstr "" + +#: ../../c-api/unicode.rst:326 +msgid "" +"Return the low UTF-16 surrogate (``0xDC00`` to ``0xDFFF``) for a Unicode " +"code point in the range ``[0x10000; 0x10FFFF]``." +msgstr "" + +#: ../../c-api/unicode.rst:331 +msgid "" +"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]." +"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:338 msgid "Creating and accessing Unicode strings" msgstr "" -#: ../../c-api/unicode.rst:329 +#: ../../c-api/unicode.rst:340 msgid "" "To create Unicode objects and access their basic sequence properties, use " "these APIs:" msgstr "" -#: ../../c-api/unicode.rst:334 +#: ../../c-api/unicode.rst:345 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:349 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:352 +msgid "On error, set an exception and return ``NULL``." +msgstr "" + +#: ../../c-api/unicode.rst:360 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 +453,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:365 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 +461,7 @@ msgid "" "range, it will be transformed into UCS1 (:c:macro:`PyUnicode_1BYTE_KIND`)." msgstr "" -#: ../../c-api/unicode.rst:363 +#: ../../c-api/unicode.rst:376 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 +469,29 @@ msgid "" "data is not allowed." msgstr "" -#: ../../c-api/unicode.rst:369 +#: ../../c-api/unicode.rst:382 msgid "This function raises :exc:`SystemError` when:" msgstr "" -#: ../../c-api/unicode.rst:371 +#: ../../c-api/unicode.rst:384 msgid "*size* < 0," msgstr "" -#: ../../c-api/unicode.rst:372 +#: ../../c-api/unicode.rst:385 msgid "*str* is ``NULL`` and *size* > 0" msgstr "" -#: ../../c-api/unicode.rst:374 +#: ../../c-api/unicode.rst:387 msgid "*str* == ``NULL`` with *size* > 0 is not allowed anymore." msgstr "" -#: ../../c-api/unicode.rst:380 +#: ../../c-api/unicode.rst:393 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:399 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 +500,7 @@ msgid "" "*format* ASCII-encoded string." msgstr "" -#: ../../c-api/unicode.rst:392 +#: ../../c-api/unicode.rst:405 msgid "" "A conversion specifier contains two or more characters and has the following " "components, which must occur in this order:" @@ -421,11 +508,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:408 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:410 msgid "" "Conversion flags (optional), which affect the result of some conversion " "types." @@ -433,7 +520,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:413 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 +528,7 @@ msgid "" "optional precision." msgstr "" -#: ../../c-api/unicode.rst:405 +#: ../../c-api/unicode.rst:418 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 +536,316 @@ msgid "" "comes after the precision." msgstr "" -#: ../../c-api/unicode.rst:410 +#: ../../c-api/unicode.rst:423 msgid "Length modifier (optional)." -msgstr "Modificador de Comprimento(opcional)." +msgstr "Modificador de comprimento (opcional)." -#: ../../c-api/unicode.rst:412 +#: ../../c-api/unicode.rst:425 msgid "Conversion type." -msgstr "Tipos de Conversão" +msgstr "Tipo de conversão." -#: ../../c-api/unicode.rst:414 +#: ../../c-api/unicode.rst:427 msgid "The conversion flag characters are:" msgstr "Os caracteres flags de conversão são:" -#: ../../c-api/unicode.rst:419 +#: ../../c-api/unicode.rst:432 msgid "Flag" msgstr "Sinalizador" -#: ../../c-api/unicode.rst:419 +#: ../../c-api/unicode.rst:432 msgid "Meaning" msgstr "Significado" -#: ../../c-api/unicode.rst:421 +#: ../../c-api/unicode.rst:434 msgid "``0``" msgstr "``0``" -#: ../../c-api/unicode.rst:421 +#: ../../c-api/unicode.rst:434 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:436 msgid "``-``" -msgstr "" +msgstr "``-``" -#: ../../c-api/unicode.rst:423 +#: ../../c-api/unicode.rst:436 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:440 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:447 msgid "Modifier" msgstr "" -#: ../../c-api/unicode.rst:434 +#: ../../c-api/unicode.rst:447 msgid "Types" msgstr "Tipos" -#: ../../c-api/unicode.rst:436 +#: ../../c-api/unicode.rst:449 msgid "``l``" msgstr "``l``" -#: ../../c-api/unicode.rst:436 +#: ../../c-api/unicode.rst:449 msgid ":c:expr:`long` or :c:expr:`unsigned long`" msgstr "" -#: ../../c-api/unicode.rst:438 +#: ../../c-api/unicode.rst:451 msgid "``ll``" -msgstr "" +msgstr "``ll``" -#: ../../c-api/unicode.rst:438 +#: ../../c-api/unicode.rst:451 msgid ":c:expr:`long long` or :c:expr:`unsigned long long`" msgstr "" -#: ../../c-api/unicode.rst:440 +#: ../../c-api/unicode.rst:453 msgid "``j``" -msgstr "" +msgstr "``j``" -#: ../../c-api/unicode.rst:440 +#: ../../c-api/unicode.rst:453 msgid ":c:type:`intmax_t` or :c:type:`uintmax_t`" msgstr "" -#: ../../c-api/unicode.rst:442 +#: ../../c-api/unicode.rst:455 msgid "``z``" -msgstr "" +msgstr "``z``" -#: ../../c-api/unicode.rst:442 +#: ../../c-api/unicode.rst:455 msgid ":c:type:`size_t` or :c:type:`ssize_t`" msgstr "" -#: ../../c-api/unicode.rst:444 +#: ../../c-api/unicode.rst:457 msgid "``t``" -msgstr "" +msgstr "``t``" -#: ../../c-api/unicode.rst:444 +#: ../../c-api/unicode.rst:457 msgid ":c:type:`ptrdiff_t`" msgstr "" -#: ../../c-api/unicode.rst:447 +#: ../../c-api/unicode.rst:460 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:463 msgid "The conversion specifiers are:" msgstr "" -#: ../../c-api/unicode.rst:456 +#: ../../c-api/unicode.rst:469 msgid "Conversion Specifier" msgstr "" -#: ../../c-api/unicode.rst:457 +#: ../../c-api/unicode.rst:470 msgid "Type" msgstr "Tipo" -#: ../../c-api/unicode.rst:458 +#: ../../c-api/unicode.rst:471 msgid "Comment" msgstr "Comentário" -#: ../../c-api/unicode.rst:460 +#: ../../c-api/unicode.rst:473 msgid "``%``" msgstr "``%``" -#: ../../c-api/unicode.rst:461 +#: ../../c-api/unicode.rst:474 msgid "*n/a*" msgstr "*n/d*" -#: ../../c-api/unicode.rst:462 +#: ../../c-api/unicode.rst:475 msgid "The literal ``%`` character." msgstr "" -#: ../../c-api/unicode.rst:464 +#: ../../c-api/unicode.rst:477 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:478 ../../c-api/unicode.rst:482 +#: ../../c-api/unicode.rst:486 ../../c-api/unicode.rst:490 +#: ../../c-api/unicode.rst:494 msgid "Specified by the length modifier" msgstr "" -#: ../../c-api/unicode.rst:466 +#: ../../c-api/unicode.rst:479 msgid "The decimal representation of a signed C integer." msgstr "" -#: ../../c-api/unicode.rst:468 +#: ../../c-api/unicode.rst:481 msgid "``u``" -msgstr "" +msgstr "``u``" -#: ../../c-api/unicode.rst:470 +#: ../../c-api/unicode.rst:483 msgid "The decimal representation of an unsigned C integer." msgstr "" -#: ../../c-api/unicode.rst:472 +#: ../../c-api/unicode.rst:485 msgid "``o``" msgstr "``o``" -#: ../../c-api/unicode.rst:474 +#: ../../c-api/unicode.rst:487 msgid "The octal representation of an unsigned C integer." msgstr "" -#: ../../c-api/unicode.rst:476 +#: ../../c-api/unicode.rst:489 msgid "``x``" msgstr "``x``" -#: ../../c-api/unicode.rst:478 +#: ../../c-api/unicode.rst:491 msgid "The hexadecimal representation of an unsigned C integer (lowercase)." msgstr "" -#: ../../c-api/unicode.rst:480 +#: ../../c-api/unicode.rst:493 msgid "``X``" -msgstr "" +msgstr "``X``" -#: ../../c-api/unicode.rst:482 +#: ../../c-api/unicode.rst:495 msgid "The hexadecimal representation of an unsigned C integer (uppercase)." msgstr "" -#: ../../c-api/unicode.rst:484 +#: ../../c-api/unicode.rst:497 msgid "``c``" msgstr "``c``" -#: ../../c-api/unicode.rst:485 +#: ../../c-api/unicode.rst:498 msgid ":c:expr:`int`" msgstr ":c:expr:`int`" -#: ../../c-api/unicode.rst:486 +#: ../../c-api/unicode.rst:499 msgid "A single character." msgstr "" -#: ../../c-api/unicode.rst:488 +#: ../../c-api/unicode.rst:501 msgid "``s``" msgstr "``s``" -#: ../../c-api/unicode.rst:489 +#: ../../c-api/unicode.rst:502 msgid ":c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: ../../c-api/unicode.rst:490 +#: ../../c-api/unicode.rst:503 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:505 msgid "``p``" msgstr "``p``" -#: ../../c-api/unicode.rst:493 +#: ../../c-api/unicode.rst:506 msgid ":c:expr:`const void*`" msgstr "" -#: ../../c-api/unicode.rst:494 +#: ../../c-api/unicode.rst:507 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:512 msgid "``A``" -msgstr "" +msgstr "``A``" -#: ../../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:513 ../../c-api/unicode.rst:517 +#: ../../c-api/unicode.rst:527 ../../c-api/unicode.rst:531 +#: ../../c-api/unicode.rst:535 ../../c-api/unicode.rst:540 msgid ":c:expr:`PyObject*`" msgstr "" -#: ../../c-api/unicode.rst:501 +#: ../../c-api/unicode.rst:514 msgid "The result of calling :func:`ascii`." msgstr "" -#: ../../c-api/unicode.rst:503 +#: ../../c-api/unicode.rst:516 msgid "``U``" -msgstr "" +msgstr "``U``" -#: ../../c-api/unicode.rst:505 +#: ../../c-api/unicode.rst:518 msgid "A Unicode object." msgstr "" -#: ../../c-api/unicode.rst:507 +#: ../../c-api/unicode.rst:520 msgid "``V``" -msgstr "" +msgstr "``V``" -#: ../../c-api/unicode.rst:508 +#: ../../c-api/unicode.rst:521 msgid ":c:expr:`PyObject*`, :c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: ../../c-api/unicode.rst:509 +#: ../../c-api/unicode.rst:522 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:526 msgid "``S``" -msgstr "" +msgstr "``S``" -#: ../../c-api/unicode.rst:515 +#: ../../c-api/unicode.rst:528 msgid "The result of calling :c:func:`PyObject_Str`." msgstr "" -#: ../../c-api/unicode.rst:517 +#: ../../c-api/unicode.rst:530 msgid "``R``" -msgstr "" +msgstr "``R``" -#: ../../c-api/unicode.rst:519 +#: ../../c-api/unicode.rst:532 msgid "The result of calling :c:func:`PyObject_Repr`." msgstr "" -#: ../../c-api/unicode.rst:521 +#: ../../c-api/unicode.rst:534 msgid "``T``" -msgstr "" +msgstr "``T``" -#: ../../c-api/unicode.rst:523 +#: ../../c-api/unicode.rst:536 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:539 msgid "``#T``" -msgstr "" +msgstr "``#T``" -#: ../../c-api/unicode.rst:528 +#: ../../c-api/unicode.rst:541 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:544 msgid "``N``" msgstr "``N``" -#: ../../c-api/unicode.rst:532 ../../c-api/unicode.rst:537 +#: ../../c-api/unicode.rst:545 ../../c-api/unicode.rst:550 msgid ":c:expr:`PyTypeObject*`" msgstr "" -#: ../../c-api/unicode.rst:533 +#: ../../c-api/unicode.rst:546 msgid "" "Get the fully qualified name of a type; call :c:func:" "`PyType_GetFullyQualifiedName`." msgstr "" -#: ../../c-api/unicode.rst:536 +#: ../../c-api/unicode.rst:549 msgid "``#N``" -msgstr "" +msgstr "``#N``" -#: ../../c-api/unicode.rst:538 +#: ../../c-api/unicode.rst:551 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:555 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 +855,28 @@ msgid "" "``PyObject*`` argument is not ``NULL``)." msgstr "" -#: ../../c-api/unicode.rst:550 +#: ../../c-api/unicode.rst:563 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:567 msgid "Support for ``\"%lld\"`` and ``\"%llu\"`` added." msgstr "Suporte adicionado para ``\"%lld\"`` e ``\"%llu\"``." -#: ../../c-api/unicode.rst:557 +#: ../../c-api/unicode.rst:570 msgid "Support for ``\"%li\"``, ``\"%lli\"`` and ``\"%zi\"`` added." msgstr "" -#: ../../c-api/unicode.rst:560 +#: ../../c-api/unicode.rst:573 msgid "" "Support width and precision formatter for ``\"%s\"``, ``\"%A\"``, " "``\"%U\"``, ``\"%V\"``, ``\"%S\"``, ``\"%R\"`` added." msgstr "" -#: ../../c-api/unicode.rst:564 +#: ../../c-api/unicode.rst:577 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 +885,50 @@ msgid "" "flag ``-``." msgstr "" -#: ../../c-api/unicode.rst:572 +#: ../../c-api/unicode.rst:585 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:589 msgid "Support for ``%T``, ``%#T``, ``%N`` and ``%#N`` formats added." msgstr "" -#: ../../c-api/unicode.rst:582 +#: ../../c-api/unicode.rst:595 msgid "" "Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two " "arguments." msgstr "" -#: ../../c-api/unicode.rst:588 +#: ../../c-api/unicode.rst:601 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:605 msgid "" "Objects other than Unicode or its subtypes will cause a :exc:`TypeError`." msgstr "" -#: ../../c-api/unicode.rst:598 +#: ../../c-api/unicode.rst:610 +msgid "Create a Unicode Object from the given Unicode code point *ordinal*." +msgstr "" + +#: ../../c-api/unicode.rst:612 +msgid "" +"The ordinal must be in ``range(0x110000)``. A :exc:`ValueError` is raised in " +"the case it is not." +msgstr "" + +#: ../../c-api/unicode.rst:619 msgid "Decode an encoded object *obj* to a Unicode object." msgstr "" -#: ../../c-api/unicode.rst:600 +#: ../../c-api/unicode.rst:621 msgid "" ":class:`bytes`, :class:`bytearray` and other :term:`bytes-like objects " "` are decoded according to the given *encoding* and using " @@ -839,23 +936,48 @@ msgid "" "interface use the default values (see :ref:`builtincodecs` for details)." msgstr "" -#: ../../c-api/unicode.rst:606 +#: ../../c-api/unicode.rst:627 msgid "" "All other objects, including Unicode objects, cause a :exc:`TypeError` to be " "set." msgstr "" -#: ../../c-api/unicode.rst:609 +#: ../../c-api/unicode.rst:630 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:636 +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:646 +msgid "" +"Return the name of the default string encoding, ``\"utf-8\"``. See :func:" +"`sys.getdefaultencoding`." +msgstr "" + +#: ../../c-api/unicode.rst:649 +msgid "" +"The returned string does not need to be freed, and is valid until " +"interpreter shutdown." +msgstr "" + +#: ../../c-api/unicode.rst:655 msgid "Return the length of the Unicode object, in code points." msgstr "" -#: ../../c-api/unicode.rst:626 +#: ../../c-api/unicode.rst:657 +msgid "On error, set an exception and return ``-1``." +msgstr "" + +#: ../../c-api/unicode.rst:668 msgid "" "Copy characters from one Unicode object into another. This function " "performs character conversion when necessary and falls back to :c:func:`!" @@ -863,52 +985,61 @@ msgid "" "otherwise returns the number of copied characters." msgstr "" -#: ../../c-api/unicode.rst:637 +#: ../../c-api/unicode.rst:679 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:682 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:685 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:694 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:698 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:702 +msgid "Return ``0`` on success, ``-1`` on error with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:709 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:713 +msgid "Return character on success, ``-1`` on error with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:721 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:731 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 +1047,7 @@ msgid "" "*unicode*). *buffer* is returned on success." msgstr "" -#: ../../c-api/unicode.rst:694 +#: ../../c-api/unicode.rst:741 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 +1055,17 @@ msgid "" "appended." msgstr "" -#: ../../c-api/unicode.rst:703 +#: ../../c-api/unicode.rst:750 msgid "Locale Encoding" msgstr "" -#: ../../c-api/unicode.rst:705 +#: ../../c-api/unicode.rst:752 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:759 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 +1074,21 @@ msgid "" "null character but cannot contain embedded null characters." msgstr "" -#: ../../c-api/unicode.rst:719 +#: ../../c-api/unicode.rst:766 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:769 ../../c-api/unicode.rst:804 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:773 ../../c-api/unicode.rst:889 msgid "The :c:func:`Py_DecodeLocale` function." msgstr "" -#: ../../c-api/unicode.rst:730 +#: ../../c-api/unicode.rst:777 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -965,13 +1096,13 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: ../../c-api/unicode.rst:739 +#: ../../c-api/unicode.rst:786 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:794 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 +1111,17 @@ msgid "" "`bytes` object. *unicode* cannot contain embedded null characters." msgstr "" -#: ../../c-api/unicode.rst:754 +#: ../../c-api/unicode.rst:801 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:808 ../../c-api/unicode.rst:920 msgid "The :c:func:`Py_EncodeLocale` function." msgstr "" -#: ../../c-api/unicode.rst:765 +#: ../../c-api/unicode.rst:812 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -998,103 +1129,124 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: ../../c-api/unicode.rst:774 +#: ../../c-api/unicode.rst:821 msgid "File System Encoding" msgstr "" -#: ../../c-api/unicode.rst:776 +#: ../../c-api/unicode.rst:823 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:826 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:832 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:844 +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:849 ../../c-api/unicode.rst:876 msgid "Accepts a :term:`path-like object`." msgstr "Aceita um :term:`objeto caminho ou similar`." -#: ../../c-api/unicode.rst:796 +#: ../../c-api/unicode.rst:852 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:858 +msgid "" +":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:871 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." +"If *obj* is ``NULL``, release the strong reference to the object referred to " +"by *result* and return ``1``." msgstr "" -#: ../../c-api/unicode.rst:816 +#: ../../c-api/unicode.rst:882 msgid "Decode a string from the :term:`filesystem encoding and error handler`." msgstr "" -#: ../../c-api/unicode.rst:818 +#: ../../c-api/unicode.rst:884 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:891 ../../c-api/unicode.rst:904 +#: ../../c-api/unicode.rst:924 msgid "" "The :term:`filesystem error handler ` " "is now used." msgstr "" -#: ../../c-api/unicode.rst:832 +#: ../../c-api/unicode.rst:898 msgid "" "Decode a null-terminated string from the :term:`filesystem encoding and " "error handler`." msgstr "" -#: ../../c-api/unicode.rst:835 +#: ../../c-api/unicode.rst:901 msgid "" "If the string length is known, use :c:func:" "`PyUnicode_DecodeFSDefaultAndSize`." msgstr "" -#: ../../c-api/unicode.rst:845 +#: ../../c-api/unicode.rst:911 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:915 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:929 msgid "wchar_t Support" msgstr "" -#: ../../c-api/unicode.rst:865 +#: ../../c-api/unicode.rst:931 msgid ":c:type:`wchar_t` support for platforms which support it:" msgstr "" -#: ../../c-api/unicode.rst:869 +#: ../../c-api/unicode.rst:935 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 +1254,7 @@ msgid "" "failure." msgstr "" -#: ../../c-api/unicode.rst:877 +#: ../../c-api/unicode.rst:943 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 +1262,13 @@ msgid "" "`wchar_t` characters copied or ``-1`` in case of an error." msgstr "" -#: ../../c-api/unicode.rst:882 +#: ../../c-api/unicode.rst:948 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:951 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 +1278,7 @@ msgid "" "most C functions." msgstr "" -#: ../../c-api/unicode.rst:895 +#: ../../c-api/unicode.rst:961 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 +1289,37 @@ msgid "" "`wchar_t*` string contains null characters a :exc:`ValueError` is raised." msgstr "" -#: ../../c-api/unicode.rst:903 +#: ../../c-api/unicode.rst:969 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:976 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:984 msgid "Built-in Codecs" msgstr "" -#: ../../c-api/unicode.rst:920 +#: ../../c-api/unicode.rst:986 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:989 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:993 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 +1327,28 @@ msgid "" "handler` internally." msgstr "" -#: ../../c-api/unicode.rst:932 +#: ../../c-api/unicode.rst:998 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:1002 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:1007 msgid "Generic Codecs" msgstr "" -#: ../../c-api/unicode.rst:943 +#: ../../c-api/unicode.rst:1009 msgid "These are the generic codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:949 +#: ../../c-api/unicode.rst:1015 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 +1357,7 @@ msgid "" "was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:959 +#: ../../c-api/unicode.rst:1025 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 +1366,21 @@ msgid "" "was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:967 +#: ../../c-api/unicode.rst:1033 msgid "UTF-8 Codecs" msgstr "" -#: ../../c-api/unicode.rst:969 +#: ../../c-api/unicode.rst:1035 msgid "These are the UTF-8 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:974 +#: ../../c-api/unicode.rst:1040 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:1047 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 +1388,20 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:989 +#: ../../c-api/unicode.rst:1055 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:1059 ../../c-api/unicode.rst:1074 +msgid "" +"The function fails if the string contains surrogate code points (``U+D800`` " +"- ``U+DFFF``)." +msgstr "" + +#: ../../c-api/unicode.rst:1065 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 +1410,13 @@ msgid "" "regardless of whether there are any other null code points." msgstr "" -#: ../../c-api/unicode.rst:1002 +#: ../../c-api/unicode.rst:1071 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:1077 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 +1425,57 @@ msgid "" "collected." msgstr "" -#: ../../c-api/unicode.rst:1012 ../../c-api/unicode.rst:1025 +#: ../../c-api/unicode.rst:1084 ../../c-api/unicode.rst:1106 msgid "The return type is now ``const char *`` rather of ``char *``." msgstr "" -#: ../../c-api/unicode.rst:1015 +#: ../../c-api/unicode.rst:1087 msgid "This function is a part of the :ref:`limited API `." msgstr "" -#: ../../c-api/unicode.rst:1021 +#: ../../c-api/unicode.rst:1093 msgid "As :c:func:`PyUnicode_AsUTF8AndSize`, but does not store the size." msgstr "" -#: ../../c-api/unicode.rst:1030 +#: ../../c-api/unicode.rst:1097 +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:1111 msgid "UTF-32 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1032 +#: ../../c-api/unicode.rst:1113 msgid "These are the UTF-32 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1038 +#: ../../c-api/unicode.rst:1119 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:1123 ../../c-api/unicode.rst:1173 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:1126 ../../c-api/unicode.rst:1176 +msgid "" +"*byteorder == -1: little endian\n" +"*byteorder == 0: native order\n" +"*byteorder == 1: big endian" +msgstr "" + +#: ../../c-api/unicode.rst:1130 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 +1483,21 @@ msgid "" "``-1`` or ``1``, any byte order mark is copied to the output." msgstr "" -#: ../../c-api/unicode.rst:1054 +#: ../../c-api/unicode.rst:1135 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:1138 ../../c-api/unicode.rst:1189 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:1140 ../../c-api/unicode.rst:1191 msgid "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: ../../c-api/unicode.rst:1065 +#: ../../c-api/unicode.rst:1146 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF32Stateful` will not " @@ -1331,29 +1506,29 @@ msgid "" "number of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1074 +#: ../../c-api/unicode.rst:1155 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:1161 msgid "UTF-16 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1082 +#: ../../c-api/unicode.rst:1163 msgid "These are the UTF-16 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1088 +#: ../../c-api/unicode.rst:1169 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:1180 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 +1537,13 @@ msgid "" "result in either a ``\\ufeff`` or a ``\\ufffe`` character)." msgstr "" -#: ../../c-api/unicode.rst:1105 +#: ../../c-api/unicode.rst:1186 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:1197 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF16Stateful` will not " @@ -1378,28 +1553,28 @@ msgid "" "*consumed*." msgstr "" -#: ../../c-api/unicode.rst:1125 +#: ../../c-api/unicode.rst:1206 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:1212 msgid "UTF-7 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1133 +#: ../../c-api/unicode.rst:1214 msgid "These are the UTF-7 codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1138 +#: ../../c-api/unicode.rst:1219 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:1226 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 +1582,101 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1152 +#: ../../c-api/unicode.rst:1233 msgid "Unicode-Escape Codecs" msgstr "" -#: ../../c-api/unicode.rst:1154 +#: ../../c-api/unicode.rst:1235 msgid "These are the \"Unicode Escape\" codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1160 +#: ../../c-api/unicode.rst:1241 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:1247 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:1253 msgid "Raw-Unicode-Escape Codecs" msgstr "" -#: ../../c-api/unicode.rst:1174 +#: ../../c-api/unicode.rst:1255 msgid "These are the \"Raw Unicode Escape\" codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1180 +#: ../../c-api/unicode.rst:1261 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:1267 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:1273 msgid "Latin-1 Codecs" msgstr "" -#: ../../c-api/unicode.rst:1194 +#: ../../c-api/unicode.rst:1275 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:1281 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:1287 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:1293 msgid "ASCII Codecs" msgstr "" -#: ../../c-api/unicode.rst:1214 +#: ../../c-api/unicode.rst:1295 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:1301 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:1307 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:1313 msgid "Character Map Codecs" msgstr "" -#: ../../c-api/unicode.rst:1234 +#: ../../c-api/unicode.rst:1315 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 +1686,18 @@ msgid "" "sequences work well." msgstr "" -#: ../../c-api/unicode.rst:1240 +#: ../../c-api/unicode.rst:1321 msgid "These are the mapping codec APIs:" msgstr "" -#: ../../c-api/unicode.rst:1245 +#: ../../c-api/unicode.rst:1326 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:1330 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 +1707,14 @@ msgid "" "treated as undefined mappings and cause an error." msgstr "" -#: ../../c-api/unicode.rst:1260 +#: ../../c-api/unicode.rst:1341 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:1345 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 +1722,41 @@ msgid "" "``None`` are treated as \"undefined mapping\" and cause an error." msgstr "" -#: ../../c-api/unicode.rst:1270 +#: ../../c-api/unicode.rst:1351 msgid "The following codec API is special in that maps Unicode to Unicode." msgstr "" -#: ../../c-api/unicode.rst:1274 +#: ../../c-api/unicode.rst:1355 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:1359 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:1362 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:1366 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:1371 msgid "MBCS codecs for Windows" msgstr "" -#: ../../c-api/unicode.rst:1292 +#: ../../c-api/unicode.rst:1373 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 +1764,13 @@ msgid "" "is defined by the user settings on the machine running the codec." msgstr "" -#: ../../c-api/unicode.rst:1299 +#: ../../c-api/unicode.rst:1380 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:1387 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeMBCSStateful` will not " @@ -1603,44 +1778,46 @@ msgid "" "will be stored in *consumed*." msgstr "" -#: ../../c-api/unicode.rst:1314 +#: ../../c-api/unicode.rst:1396 +msgid "" +"Similar to :c:func:`PyUnicode_DecodeMBCSStateful`, except uses the code page " +"specified by *code_page*." +msgstr "" + +#: ../../c-api/unicode.rst:1402 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:1409 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 -msgid "Methods & Slots" -msgstr "" - -#: ../../c-api/unicode.rst:1335 +#: ../../c-api/unicode.rst:1419 msgid "Methods and Slot Functions" msgstr "" -#: ../../c-api/unicode.rst:1337 +#: ../../c-api/unicode.rst:1421 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:1425 msgid "They all return ``NULL`` or ``-1`` if an exception occurs." msgstr "" -#: ../../c-api/unicode.rst:1346 +#: ../../c-api/unicode.rst:1430 msgid "Concat two strings giving a new Unicode string." msgstr "" -#: ../../c-api/unicode.rst:1351 +#: ../../c-api/unicode.rst:1435 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 +1826,73 @@ msgid "" "list." msgstr "" -#: ../../c-api/unicode.rst:1359 +#: ../../c-api/unicode.rst:1440 ../../c-api/unicode.rst:1450 +#: ../../c-api/unicode.rst:1471 ../../c-api/unicode.rst:1484 +msgid "On error, return ``NULL`` with an exception set." +msgstr "" + +#: ../../c-api/unicode.rst:1442 +msgid "Equivalent to :py:meth:`str.split`." +msgstr "" + +#: ../../c-api/unicode.rst:1447 +msgid "" +"Similar to :c:func:`PyUnicode_Split`, but splitting will be done beginning " +"at the end of the string." +msgstr "" + +#: ../../c-api/unicode.rst:1452 +msgid "Equivalent to :py:meth:`str.rsplit`." +msgstr "" + +#: ../../c-api/unicode.rst:1457 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:1464 +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:1469 ../../c-api/unicode.rst:1482 +msgid "*sep* must not be empty." +msgstr "" + +#: ../../c-api/unicode.rst:1473 +msgid "Equivalent to :py:meth:`str.partition`." +msgstr "" + +#: ../../c-api/unicode.rst:1478 +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:1486 +msgid "Equivalent to :py:meth:`str.rpartition`." +msgstr "" + +#: ../../c-api/unicode.rst:1491 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:1498 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:1506 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 +1901,7 @@ msgid "" "``-2`` indicates that an error occurred and an exception has been set." msgstr "" -#: ../../c-api/unicode.rst:1391 +#: ../../c-api/unicode.rst:1516 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 +1911,57 @@ msgid "" "set." msgstr "" -#: ../../c-api/unicode.rst:1399 +#: ../../c-api/unicode.rst:1524 msgid "" "*start* and *end* are now adjusted to behave like ``unicode[start:end]``." msgstr "" -#: ../../c-api/unicode.rst:1406 +#: ../../c-api/unicode.rst:1531 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:1538 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:1545 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:1548 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:1554 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:1561 ../../c-api/unicode.rst:1582 msgid "This function does not raise exceptions." msgstr "" -#: ../../c-api/unicode.rst:1442 +#: ../../c-api/unicode.rst:1568 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:1577 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 +1969,47 @@ msgid "" "string as ISO-8859-1 if it contains non-ASCII characters." msgstr "" -#: ../../c-api/unicode.rst:1461 +#: ../../c-api/unicode.rst:1587 msgid "Rich compare two Unicode strings and return one of the following:" msgstr "" -#: ../../c-api/unicode.rst:1463 +#: ../../c-api/unicode.rst:1589 msgid "``NULL`` in case an exception was raised" msgstr "" -#: ../../c-api/unicode.rst:1464 +#: ../../c-api/unicode.rst:1590 msgid ":c:data:`Py_True` or :c:data:`Py_False` for successful comparisons" msgstr "" -#: ../../c-api/unicode.rst:1465 +#: ../../c-api/unicode.rst:1591 msgid ":c:data:`Py_NotImplemented` in case the type combination is unknown" msgstr "" -#: ../../c-api/unicode.rst:1467 +#: ../../c-api/unicode.rst:1593 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:1599 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:1605 msgid "" "Check whether *substr* is contained in *unicode* and return true or false " "accordingly." msgstr "" -#: ../../c-api/unicode.rst:1482 +#: ../../c-api/unicode.rst:1608 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:1614 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 +2020,7 @@ msgid "" "interns it." msgstr "" -#: ../../c-api/unicode.rst:1495 +#: ../../c-api/unicode.rst:1621 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 +2028,39 @@ msgid "" "the result.)" msgstr "" -#: ../../c-api/unicode.rst:1500 +#: ../../c-api/unicode.rst:1626 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:1629 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:1633 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:1639 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:1642 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:1646 msgid "" "Python may keep a reference to the result, or make it :term:`immortal`, " "preventing it from being garbage-collected promptly. For interning an " @@ -1844,7 +2068,3 @@ msgid "" "prefer calling :c:func:`PyUnicode_FromString` and :c:func:" "`PyUnicode_InternInPlace` directly." msgstr "" - -#: ../../c-api/unicode.rst:1528 -msgid "Strings interned this way are made :term:`immortal`." -msgstr "" diff --git a/c-api/utilities.po b/c-api/utilities.po index 1de7d47e7..66467f0e4 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..cb020e00a 100644 --- a/c-api/veryhigh.po +++ b/c-api/veryhigh.po @@ -1,32 +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 -# Rafael Fontenelle , 2023 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,16 +34,25 @@ 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 "" "Several of these functions accept a start symbol from the grammar as a " "parameter. The available start symbols are :c:data:`Py_eval_input`, :c:data:" -"`Py_file_input`, and :c:data:`Py_single_input`. These are described " -"following the functions which accept them as parameters." +"`Py_file_input`, :c:data:`Py_single_input`, and :c:data:" +"`Py_func_type_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` e :c:data:" +"`Py_func_type_input`. Eles são descritos seguindo as funções que os aceitam " +"como parâmetros." -#: ../../c-api/veryhigh.rst:19 +#: ../../c-api/veryhigh.rst:20 msgid "" "Note also that several of these functions take :c:expr:`FILE*` parameters. " "One particular issue which needs to be handled carefully is that the :c:type:" @@ -54,50 +63,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 +#: ../../c-api/veryhigh.rst:31 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:37 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:43 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:49 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 +107,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:61 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:67 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 +133,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:73 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:80 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:86 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:92 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 +174,31 @@ 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:99 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 -msgid "" -"This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below, " -"leaving *flags* set to ``NULL``." -msgstr "" - -#: ../../c-api/veryhigh.rst:134 +#: ../../c-api/veryhigh.rst:105 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`." +"prompted using ``sys.ps1`` and ``sys.ps2``. *filename* must be a Python :" +"class:`str` object." msgstr "" -#: ../../c-api/veryhigh.rst:139 +#: ../../c-api/veryhigh.rst:110 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,38 +206,73 @@ 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:119 +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:148 +#: ../../c-api/veryhigh.rst:125 +msgid "" +"Similar to :c:func:`PyRun_InteractiveOneObject`, but *filename* is a :c:expr:" +"`const char*`, which is decoded from the :term:`filesystem encoding and " +"error handler`." +msgstr "" + +#: ../../c-api/veryhigh.rst:132 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:138 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:146 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 " "become idle and wait for user input from the terminal. The return value is " "ignored. Overriding this hook can be used to integrate the interpreter's " -"prompt with other event loops, as done in the :file:`Modules/_tkinter.c` in " -"the Python source code." +"prompt with other event loops, as done in :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:154 ../../c-api/veryhigh.rst:178 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:161 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,60 +282,89 @@ 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:170 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:173 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:184 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:190 msgid "" "Execute Python source code from *str* in the context specified by the " "objects *globals* and *locals* with the compiler flags specified by " "*flags*. *globals* must be a dictionary; *locals* can be any object that " "implements the mapping protocol. The parameter *start* specifies the start " -"token that should be used to parse the source code." +"symbol and must one of the :ref:`available start symbols `." 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 " +"símbolo inicial e deve ser um dos :ref:`símbolos iniciais disponíveis `." -#: ../../c-api/veryhigh.rst:212 +#: ../../c-api/veryhigh.rst:196 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:202 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:208 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:214 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:220 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,31 +372,47 @@ 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:229 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:235 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:241 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 " -"constrain the code which can be compiled and should be :c:data:" -"`Py_eval_input`, :c:data:`Py_file_input`, or :c:data:`Py_single_input`. The " -"filename specified by *filename* is used to construct the code object and " -"may appear in tracebacks or :exc:`SyntaxError` exception messages. This " -"returns ``NULL`` if the code cannot be parsed or compiled." -msgstr "" - -#: ../../c-api/veryhigh.rst:265 +"code object. The start symbol is given by *start*; this can be used to " +"constrain the code which can be compiled and should be :ref:`available start " +"symbols `. The filename specified by *filename* is used to " +"construct the code object and may appear in tracebacks or :exc:`SyntaxError` " +"exception messages. This returns ``NULL`` if the code cannot be parsed or " +"compiled." +msgstr "" +"Analisa e compila o código-fonte Python em *str*, retornando o objeto de " +"código resultante. O símbolo inicial é fornecido por *start*; isso pode ser " +"usado para restringir o código que pode ser compilado e deve ser :ref:" +"`símbolos iniciais disponíveis `. 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:249 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 +420,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:260 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:267 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:274 msgid "" "Evaluate a precompiled code object, given a particular environment for its " "evaluation. This environment consists of a dictionary of global variables, " @@ -336,14 +454,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:283 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:289 msgid "" "This is the main, unvarnished function of Python interpretation. The code " "object associated with the execution frame *f* is executed, interpreting " @@ -352,8 +477,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:296 msgid "" "This function now includes a debug assertion to help ensure that it does not " "silently discard an active exception." @@ -361,74 +492,142 @@ 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:303 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 -msgid "" -"The start symbol from the Python grammar for isolated expressions; for use " -"with :c:func:`Py_CompileString`." -msgstr "" - -#: ../../c-api/veryhigh.rst:335 -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 "" - -#: ../../c-api/veryhigh.rst:344 -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 "" - -#: ../../c-api/veryhigh.rst:351 +#: ../../c-api/veryhigh.rst:309 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:314 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:320 msgid "Compiler flags." -msgstr "" +msgstr "Sinalizadores do compilador." -#: ../../c-api/veryhigh.rst:366 +#: ../../c-api/veryhigh.rst:324 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:327 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:330 msgid "Added *cf_feature_version* field." +msgstr "Adicionado campo *cf_feature_version*." + +#: ../../c-api/veryhigh.rst:333 +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:342 +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:346 msgid "" -"This bit can be set in *flags* to cause division operator ``/`` to be " -"interpreted as \"true division\" according to :pep:`238`." +"The \"``PyCF``\" flags above can be combined with \"``CO_FUTURE``\" flags " +"such as :c:macro:`CO_FUTURE_ANNOTATIONS` to enable features normally " +"selectable using :ref:`future statements `. See :ref:" +"`c_codeobject_flags` for a complete list." msgstr "" +"Os sinalizadores \"``PyCF``\" acima podem ser combinados com sinalizadores " +"\"``CO_FUTURE``\", como :c:macro:`CO_FUTURE_ANNOTATIONS`, para habilitar " +"recursos normalmente selecionáveis usando :ref:`instruções future `. " +"Consulte :ref:`c_codeobject_flags` para obter uma lista completa." -#: ../../c-api/veryhigh.rst:325 ../../c-api/veryhigh.rst:333 -#: ../../c-api/veryhigh.rst:342 -msgid "Py_CompileString (C function)" +#: ../../c-api/veryhigh.rst:355 +msgid "Available start symbols" +msgstr "Símbolos iniciais disponíveis" + +#: ../../c-api/veryhigh.rst:362 +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:370 +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:379 +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:388 +msgid "" +"The start symbol from the Python grammar for a function type; for use with :" +"c:func:`Py_CompileString`. This is used to parse \"signature type comments\" " +"from :pep:`484`." +msgstr "" +"O símbolo inicial da gramática Python para um tipo de função; para uso com :" +"c:func:`Py_CompileString`. É usado para analisar \"comentários de tipo de " +"assinatura\" de :pep:`484`." + +#: ../../c-api/veryhigh.rst:392 +msgid "This requires the :c:macro:`PyCF_ONLY_AST` flag to be set." +msgstr "Isso requer que o sinalizador :c:macro:`PyCF_ONLY_AST` seja definido." + +#: ../../c-api/veryhigh.rst:395 +msgid ":py:class:`ast.FunctionType`" +msgstr ":py:class:`ast.FunctionType`" + +#: ../../c-api/veryhigh.rst:396 +msgid ":pep:`484`" +msgstr ":pep:`484`" + +#: ../../c-api/veryhigh.rst:360 ../../c-api/veryhigh.rst:368 +#: ../../c-api/veryhigh.rst:377 ../../c-api/veryhigh.rst:386 +msgid "Py_CompileString (C function)" +msgstr "Py_CompileString (função C)" diff --git a/c-api/weakref.po b/c-api/weakref.po index 49e01717c..4b8e7b57a 100644 --- a/c-api/weakref.po +++ b/c-api/weakref.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,20 +51,28 @@ msgstr "" #: ../../c-api/weakref.rst:22 msgid "" -"Return non-zero if *ob* is a reference object. This function always " -"succeeds." +"Return non-zero if *ob* is a reference object or a subclass of the reference " +"type. This function always succeeds." msgstr "" -"Retorna não zero se *ob* for um objeto referência. Esta função sempre tem " -"sucesso." +"Retorna não zero se *ob* for um objeto referência ou uma subclasse do tipo " +"de referência. Esta função sempre tem sucesso." -#: ../../c-api/weakref.rst:27 +#: ../../c-api/weakref.rst:28 +msgid "" +"Return non-zero if *ob* is a reference object, but not a subclass of the " +"reference type. This function always succeeds." +msgstr "" +"Retorna não zero se *ob* for um objeto referência, mas não uma subclasse do " +"tipo de referência. Esta função sempre tem sucesso." + +#: ../../c-api/weakref.rst:34 msgid "" "Return non-zero if *ob* is a proxy object. This function always succeeds." msgstr "" "Retorna não zero se *ob* for um objeto intermediário. Esta função sempre tem " "sucesso." -#: ../../c-api/weakref.rst:32 +#: ../../c-api/weakref.rst:39 msgid "" "Return a weak reference object for the object *ob*. This will always return " "a new reference, but is not guaranteed to create a new object; an existing " @@ -84,7 +93,13 @@ msgstr "" "se *callback* não for um chamável, ``None``, ou ``NULL``, isso retornará " "``NULL`` e levantará a :exc:`TypeError`." -#: ../../c-api/weakref.rst:44 +#: ../../c-api/weakref.rst:49 ../../c-api/weakref.rst:65 +msgid "" +":c:func:`PyType_SUPPORTS_WEAKREFS` for checking if *ob* is weakly " +"referenceable." +msgstr "" + +#: ../../c-api/weakref.rst:55 msgid "" "Return a weak reference proxy object for the object *ob*. This will always " "return a new reference, but is not guaranteed to create a new object; an " @@ -105,7 +120,7 @@ msgstr "" "*callback* não for um chamável, ``None``, ou ``NULL``, isso retornará " "``NULL`` e levantará a :exc:`TypeError`." -#: ../../c-api/weakref.rst:56 +#: ../../c-api/weakref.rst:71 msgid "" "Get a :term:`strong reference` to the referenced object from a weak " "reference, *ref*, into *\\*pobj*." @@ -113,7 +128,7 @@ msgstr "" "Obtém uma :term:`referência forte` para o objeto referenciado a partir de " "uma referência fraca, *ref*, em *\\*pobj*." -#: ../../c-api/weakref.rst:59 +#: ../../c-api/weakref.rst:74 msgid "" "On success, set *\\*pobj* to a new :term:`strong reference` to the " "referenced object and return 1." @@ -121,16 +136,16 @@ msgstr "" "Em caso de sucesso, define *\\*pobj* como uma nova :term:`referência forte` " "para o objeto referenciado e retorna 1." -#: ../../c-api/weakref.rst:61 +#: ../../c-api/weakref.rst:76 msgid "If the reference is dead, set *\\*pobj* to ``NULL`` and return 0." msgstr "" "Se a referência estiver quebrada, define *\\*pobj* como ``NULL`` e retorna 0." -#: ../../c-api/weakref.rst:62 +#: ../../c-api/weakref.rst:77 msgid "On error, raise an exception and return -1." msgstr "Em caso de erro, levanta uma exceção e retorna -1." -#: ../../c-api/weakref.rst:69 +#: ../../c-api/weakref.rst:84 msgid "" "Return a :term:`borrowed reference` to the referenced object from a weak " "reference, *ref*. If the referent is no longer live, returns ``Py_None``." @@ -139,7 +154,7 @@ msgstr "" "uma referência fraca, *ref*. Se o referente não estiver mais em tempo real, " "retorna ``Py_None``." -#: ../../c-api/weakref.rst:74 +#: ../../c-api/weakref.rst:89 msgid "" "This function returns a :term:`borrowed reference` to the referenced object. " "This means that you should always call :c:func:`Py_INCREF` on the object " @@ -151,15 +166,15 @@ msgstr "" "no objeto, exceto quando ele não puder ser destruído antes do último uso da " "referência emprestada." -#: ../../c-api/weakref.rst:79 ../../c-api/weakref.rst:87 +#: ../../c-api/weakref.rst:94 ../../c-api/weakref.rst:102 msgid "Use :c:func:`PyWeakref_GetRef` instead." msgstr "Usa :c:func:`PyWeakref_GetRef`." -#: ../../c-api/weakref.rst:85 +#: ../../c-api/weakref.rst:100 msgid "Similar to :c:func:`PyWeakref_GetObject`, but does no error checking." msgstr "Semelhante a :c:func:`PyWeakref_GetObject`, mas não verifica erros." -#: ../../c-api/weakref.rst:93 +#: ../../c-api/weakref.rst:108 msgid "" "This function is called by the :c:member:`~PyTypeObject.tp_dealloc` handler " "to clear weak references." @@ -167,7 +182,7 @@ msgstr "" "Esta função é chamada pelo tratador :c:member:`~PyTypeObject.tp_dealloc` " "para limpar referências fracas." -#: ../../c-api/weakref.rst:96 +#: ../../c-api/weakref.rst:111 msgid "" "This iterates through the weak references for *object* and calls callbacks " "for those references which have one. It returns when all callbacks have been " @@ -177,12 +192,12 @@ msgstr "" "chamada para as referências que possuem um. Ele retorna quando todos os " "retornos de chamada foram tentados." -#: ../../c-api/weakref.rst:103 +#: ../../c-api/weakref.rst:118 msgid "Clears the weakrefs for *object* without calling the callbacks." msgstr "" "Limpa as referências fracas para *object* sem chamar as funções de retorno" -#: ../../c-api/weakref.rst:105 +#: ../../c-api/weakref.rst:120 msgid "" "This function is called by the :c:member:`~PyTypeObject.tp_dealloc` handler " "for types with finalizers (i.e., :meth:`~object.__del__`). The handler for " @@ -198,7 +213,7 @@ msgstr "" "limpar quaisquer referências fracas que possam ter sido criadas pelo " "finalizador." -#: ../../c-api/weakref.rst:111 +#: ../../c-api/weakref.rst:126 msgid "" "In most circumstances, it's more appropriate to use :c:func:" "`PyObject_ClearWeakRefs` to clear weakrefs instead of this function." diff --git a/contents.po b/contents.po index 42df5b791..20354e22b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..58b5a828c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..8b419c2ba 100644 --- a/deprecations/c-api-pending-removal-in-3.14.po +++ b/deprecations/c-api-pending-removal-in-3.14.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +52,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..46f30ffe9 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,31 +28,28 @@ msgid "Pending Removal in Python 3.15" msgstr "Remoção pendente no Python 3.15" #: ../../deprecations/c-api-pending-removal-in-3.15.rst:4 -msgid "The bundled copy of ``libmpdecimal``." -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`." +"The :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`." - -#: ../../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`." +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: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`." - -#: ../../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 msgid "Python initialization functions:" @@ -60,36 +57,43 @@ msgstr "Funções de inicialização do Python" #: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 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`." +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:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.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`." +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:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +msgid "" +":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:20 +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:22 +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:19 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:24 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :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`." diff --git a/deprecations/c-api-pending-removal-in-3.16.po b/deprecations/c-api-pending-removal-in-3.16.po new file mode 100644 index 000000000..3f8ce0864 --- /dev/null +++ b/deprecations/c-api-pending-removal-in-3.16.po @@ -0,0 +1,33 @@ +# 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: +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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" + +#: ../../deprecations/c-api-pending-removal-in-3.16.rst:2 +msgid "Pending removal in Python 3.16" +msgstr "Remoção pendente no Python 3.16" + +#: ../../deprecations/c-api-pending-removal-in-3.16.rst:4 +msgid "The bundled copy of ``libmpdec``." +msgstr "A cópia empacotada do ``libmpdec``." diff --git a/deprecations/c-api-pending-removal-in-future.po b/deprecations/c-api-pending-removal-in-future.po index 21ec83bd3..3edc5a803 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..9c64721bd 100644 --- a/deprecations/index.po +++ b/deprecations/index.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-07 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +49,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 +79,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 +94,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`.)" @@ -123,18 +125,12 @@ msgstr "" #: ../../deprecations/pending-removal-in-3.14.rst:41 msgid "" -":mod:`collections.abc`: Deprecated :class:`~collections.abc.ByteString`. " -"Prefer :class:`!Sequence` or :class:`~collections.abc.Buffer`. For use in " -"typing, prefer a union, like ``bytes | bytearray``, or :class:`collections." -"abc.Buffer`. (Contributed by Shantanu Jain in :gh:`91896`.)" +":mod:`builtins`: ``bool(NotImplemented)`` now emits a :exc:" +"`DeprecationWarning` and will raise a :exc:`TypeError` in Python 3.14. " +"(Contributed by Jelle Zijlstra in :gh:`118767`.)" 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`` " -"ou :class:`collections.abc.Buffer`. (Contribuição de Shantanu Jain em :gh:" -"`91896`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:47 +#: ../../deprecations/pending-removal-in-3.14.rst:45 msgid "" ":mod:`email`: Deprecated the *isdst* parameter in :func:`email.utils." "localtime`. (Contributed by Alan Williams in :gh:`72346`.)" @@ -142,47 +138,39 @@ msgstr "" ":mod:`email`: Descontinua o parâmetro *isdst* em :func:`email.utils." "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 +#: ../../deprecations/pending-removal-in-3.14.rst:48 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:50 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:51 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:52 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:54 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:56 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:57 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:59 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:61 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -195,7 +183,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:67 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 +193,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 +202,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:75 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -222,7 +210,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:79 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -232,65 +220,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:84 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:86 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:87 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:89 msgid ":mod:`sqlite3`:" msgstr ":mod:`sqlite3`:" -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:91 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:93 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 -msgid "" -":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " -"causes a :exc:`DeprecationWarning` to be emitted when it is used." -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:97 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 +266,418 @@ 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:55 +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:80 +#: ../../deprecations/pending-removal-in-3.17.rst:26 +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." #: ../../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 "" +"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/pending-removal-in-3.17.rst:2 +msgid "Pending removal in Python 3.17" +msgstr "Remoção pendente no Python 3.17" + +#: ../../deprecations/pending-removal-in-3.17.rst:4 +msgid ":mod:`collections.abc`:" +msgstr ":mod:`collections.abc`:" + +#: ../../deprecations/pending-removal-in-3.17.rst:6 +msgid "" +":class:`collections.abc.ByteString` is scheduled for removal in Python 3.17." +msgstr "" +":class:`collections.abc.ByteString` está agendado para remoção no Python " +"3.17." + +#: ../../deprecations/pending-removal-in-3.17.rst:8 +#: ../../deprecations/pending-removal-in-3.17.rst:36 +msgid "" +"Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj`` " +"implements the :ref:`buffer protocol ` at runtime. For use in " +"type annotations, either use :class:`~collections.abc.Buffer` or a union " +"that explicitly specifies the types your code supports (e.g., ``bytes | " +"bytearray | memoryview``)." +msgstr "" +"Use ``isinstance(obj, collections.abc.Buffer)`` para testar se ``obj`` " +"implementa o :ref:`protocolo de buffer ` em tempo de " +"execução. Para uso em anotações de tipo, use :class:`~collections.abc." +"Buffer` ou uma união que especifique explicitamente os tipos suportados pelo " +"seu código (por exemplo, ``bytes | bytearray | memoryview``)." + +#: ../../deprecations/pending-removal-in-3.17.rst:14 +#: ../../deprecations/pending-removal-in-3.17.rst:42 msgid "" -":mod:`array`: :class:`array.array` ``'u'`` type (:c:type:`wchar_t`): use the " -"``'w'`` type instead (``Py_UCS4``)." +":class:`!ByteString` was originally intended to be an abstract class that " +"would serve as a supertype of both :class:`bytes` and :class:`bytearray`. " +"However, since the ABC never had any methods, knowing that an object was an " +"instance of :class:`!ByteString` never actually told you anything useful " +"about the object. Other common buffer types such as :class:`memoryview` were " +"also never understood as subtypes of :class:`!ByteString` (either at runtime " +"or by static type checkers)." msgstr "" -":mod:`array`: :class:`array.array`: tipo ``'u'`` (:c:type:`wchar_t`): use o " -"tipo ``'w'`` (``Py_UCS4``)." +":class:`!ByteString` foi originalmente concebido para ser uma classe " +"abstrata que serviria como um supertipo de :class:`bytes` e :class:" +"`bytearray`. No entanto, como o ABC nunca teve métodos, saber que um objeto " +"era uma instância de :class:`!ByteString` nunca lhe dizia nada de útil sobre " +"o objeto. Outros tipos comuns de buffer, como :class:`memoryview`, também " +"nunca foram entendidos como subtipos de :class:`!ByteString` (seja em tempo " +"de execução ou por verificadores de tipo estáticos)." -#: ../../deprecations/pending-removal-in-3.16.rst:8 +#: ../../deprecations/pending-removal-in-3.17.rst:22 +#: ../../deprecations/pending-removal-in-3.17.rst:50 msgid "" -":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " -"lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" +"See :pep:`PEP 688 <688#current-options>` for more details. (Contributed by " +"Shantanu Jain in :gh:`91896`.)" msgstr "" -":mod:`symtable`: Descontinua :meth:`symtable.Class.get_methods` por falta de " -"interesse. (Contribuição de Bénédikt Tran em :gh:`119698`.)" +"Veja :pep:`PEP 688 <688#current-options>` para mais detalhes. (Contribuição " +"de Shantanu Jain em :gh:`91896`.)" + +#: ../../deprecations/pending-removal-in-3.17.rst:28 +msgid "" +"Before Python 3.14, old-style unions were implemented using the private " +"class ``typing._UnionGenericAlias``. This class is no longer needed for the " +"implementation, but it has been retained for backward compatibility, with " +"removal scheduled for Python 3.17. Users should use documented introspection " +"helpers like :func:`typing.get_origin` and :func:`typing.get_args` instead " +"of relying on private implementation details." +msgstr "" +"Antes do Python 3.14, as uniões antigas eram implementadas usando a classe " +"privada ``typing._UnionGenericAlias``. Essa classe não é mais necessária " +"para a implementação, mas foi mantida para compatibilidade com versões " +"anteriores, com remoção prevista para o Python 3.17. Os usuários devem usar " +"auxiliares de introspecção documentados, como :func:`typing.get_origin` e :" +"func:`typing.get_args`, em vez de depender de detalhes de implementação " +"privada." + +#: ../../deprecations/pending-removal-in-3.17.rst:33 +msgid "" +":class:`typing.ByteString`, deprecated since Python 3.9, is scheduled for " +"removal in Python 3.17." +msgstr "" +":class:`typing.ByteString`, obsoleto desde o Python 3.9, está programado " +"para ser removido no Python 3.17." #: ../../deprecations/c-api-pending-removal-in-future.rst:2 #: ../../deprecations/pending-removal-in-future.rst:2 @@ -468,36 +697,20 @@ 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 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:15 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 +731,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:23 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 +741,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:26 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 +751,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:29 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 +761,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:32 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:33 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 +777,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:38 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:43 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:46 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:48 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -593,7 +806,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:50 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -601,68 +814,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:53 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:57 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:60 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:62 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:63 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:65 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:68 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:71 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:73 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:76 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 +875,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:83 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:85 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:88 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:90 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:91 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:94 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:95 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:96 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:103 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:105 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:107 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -767,11 +964,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:108 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:109 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -779,7 +976,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:111 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -787,20 +984,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:113 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:114 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:116 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:118 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -808,7 +1005,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:121 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -816,62 +1013,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:123 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:135 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:139 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -879,7 +1076,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:142 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 +1088,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:147 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." @@ -899,7 +1096,7 @@ msgstr "" ":meth:`zipimport.zipimporter.load_module` foi descontinuado: use :meth:" "`~zipimport.zipimporter.exec_module`." -#: ../../deprecations/index.rst:13 +#: ../../deprecations/index.rst:15 msgid "C API Deprecations" msgstr "Descontinuações na API C" @@ -927,190 +1124,190 @@ 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." +#: ../../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:" "`Py_PreInitialize`)" #: ../../deprecations/c-api-pending-removal-in-3.15.rst:4 -msgid "The bundled copy of ``libmpdecimal``." -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`." +"The :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`." - -#: ../../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`." +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: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`." - -#: ../../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 msgid "Python initialization functions:" @@ -1118,161 +1315,170 @@ msgstr "Funções de inicialização do Python" #: ../../deprecations/c-api-pending-removal-in-3.15.rst:12 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`." +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:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." -msgstr ":c:func:`Py_GetPrefix`: obtenha :data:`sys.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`." +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:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." -msgstr ":c:func:`Py_GetProgramName`: obtenha :data:`sys.executable`." +msgid "" +":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:19 +#: ../../deprecations/c-api-pending-removal-in-3.15.rst:20 +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:22 +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:24 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :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`." #: ../../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..2ff7ea9d5 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..d4f7892cc 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 +# python-doc bot, 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-10-07 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 @@ -118,18 +118,12 @@ msgstr "" #: ../../deprecations/pending-removal-in-3.14.rst:41 msgid "" -":mod:`collections.abc`: Deprecated :class:`~collections.abc.ByteString`. " -"Prefer :class:`!Sequence` or :class:`~collections.abc.Buffer`. For use in " -"typing, prefer a union, like ``bytes | bytearray``, or :class:`collections." -"abc.Buffer`. (Contributed by Shantanu Jain in :gh:`91896`.)" +":mod:`builtins`: ``bool(NotImplemented)`` now emits a :exc:" +"`DeprecationWarning` and will raise a :exc:`TypeError` in Python 3.14. " +"(Contributed by Jelle Zijlstra in :gh:`118767`.)" 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`` " -"ou :class:`collections.abc.Buffer`. (Contribuição de Shantanu Jain em :gh:" -"`91896`.)" -#: ../../deprecations/pending-removal-in-3.14.rst:47 +#: ../../deprecations/pending-removal-in-3.14.rst:45 msgid "" ":mod:`email`: Deprecated the *isdst* parameter in :func:`email.utils." "localtime`. (Contributed by Alan Williams in :gh:`72346`.)" @@ -137,47 +131,39 @@ msgstr "" ":mod:`email`: Descontinua o parâmetro *isdst* em :func:`email.utils." "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 +#: ../../deprecations/pending-removal-in-3.14.rst:48 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:50 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:51 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:52 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:54 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:56 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:57 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:59 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:61 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -190,7 +176,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:67 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 +186,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 +195,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:75 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." @@ -217,7 +203,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:79 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " @@ -227,65 +213,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:84 msgid ":mod:`pty`:" msgstr ":mod:`pty`:" -#: ../../deprecations/pending-removal-in-3.14.rst:91 +#: ../../deprecations/pending-removal-in-3.14.rst:86 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:87 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:89 msgid ":mod:`sqlite3`:" msgstr ":mod:`sqlite3`:" -#: ../../deprecations/pending-removal-in-3.14.rst:96 +#: ../../deprecations/pending-removal-in-3.14.rst:91 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:93 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 -msgid "" -":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " -"causes a :exc:`DeprecationWarning` to be emitted when it is used." -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:97 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..dbbe9bd6b 100644 --- a/deprecations/pending-removal-in-3.15.po +++ b/deprecations/pending-removal-in-3.15.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +29,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..4191b32ce 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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-3.17.po b/deprecations/pending-removal-in-3.17.po new file mode 100644 index 000000000..c4480cff6 --- /dev/null +++ b/deprecations/pending-removal-in-3.17.po @@ -0,0 +1,112 @@ +# 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: +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-23 14:56+0000\n" +"PO-Revision-Date: 2025-09-19 15:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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" + +#: ../../deprecations/pending-removal-in-3.17.rst:2 +msgid "Pending removal in Python 3.17" +msgstr "Remoção pendente no Python 3.17" + +#: ../../deprecations/pending-removal-in-3.17.rst:4 +msgid ":mod:`collections.abc`:" +msgstr ":mod:`collections.abc`:" + +#: ../../deprecations/pending-removal-in-3.17.rst:6 +msgid "" +":class:`collections.abc.ByteString` is scheduled for removal in Python 3.17." +msgstr "" +":class:`collections.abc.ByteString` está agendado para remoção no Python " +"3.17." + +#: ../../deprecations/pending-removal-in-3.17.rst:8 +#: ../../deprecations/pending-removal-in-3.17.rst:36 +msgid "" +"Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj`` " +"implements the :ref:`buffer protocol ` at runtime. For use in " +"type annotations, either use :class:`~collections.abc.Buffer` or a union " +"that explicitly specifies the types your code supports (e.g., ``bytes | " +"bytearray | memoryview``)." +msgstr "" +"Use ``isinstance(obj, collections.abc.Buffer)`` para testar se ``obj`` " +"implementa o :ref:`protocolo de buffer ` em tempo de " +"execução. Para uso em anotações de tipo, use :class:`~collections.abc." +"Buffer` ou uma união que especifique explicitamente os tipos suportados pelo " +"seu código (por exemplo, ``bytes | bytearray | memoryview``)." + +#: ../../deprecations/pending-removal-in-3.17.rst:14 +#: ../../deprecations/pending-removal-in-3.17.rst:42 +msgid "" +":class:`!ByteString` was originally intended to be an abstract class that " +"would serve as a supertype of both :class:`bytes` and :class:`bytearray`. " +"However, since the ABC never had any methods, knowing that an object was an " +"instance of :class:`!ByteString` never actually told you anything useful " +"about the object. Other common buffer types such as :class:`memoryview` were " +"also never understood as subtypes of :class:`!ByteString` (either at runtime " +"or by static type checkers)." +msgstr "" +":class:`!ByteString` foi originalmente concebido para ser uma classe " +"abstrata que serviria como um supertipo de :class:`bytes` e :class:" +"`bytearray`. No entanto, como o ABC nunca teve métodos, saber que um objeto " +"era uma instância de :class:`!ByteString` nunca lhe dizia nada de útil sobre " +"o objeto. Outros tipos comuns de buffer, como :class:`memoryview`, também " +"nunca foram entendidos como subtipos de :class:`!ByteString` (seja em tempo " +"de execução ou por verificadores de tipo estáticos)." + +#: ../../deprecations/pending-removal-in-3.17.rst:22 +#: ../../deprecations/pending-removal-in-3.17.rst:50 +msgid "" +"See :pep:`PEP 688 <688#current-options>` for more details. (Contributed by " +"Shantanu Jain in :gh:`91896`.)" +msgstr "" +"Veja :pep:`PEP 688 <688#current-options>` para mais detalhes. (Contribuição " +"de Shantanu Jain em :gh:`91896`.)" + +#: ../../deprecations/pending-removal-in-3.17.rst:26 +msgid ":mod:`typing`:" +msgstr ":mod:`typing`:" + +#: ../../deprecations/pending-removal-in-3.17.rst:28 +msgid "" +"Before Python 3.14, old-style unions were implemented using the private " +"class ``typing._UnionGenericAlias``. This class is no longer needed for the " +"implementation, but it has been retained for backward compatibility, with " +"removal scheduled for Python 3.17. Users should use documented introspection " +"helpers like :func:`typing.get_origin` and :func:`typing.get_args` instead " +"of relying on private implementation details." +msgstr "" +"Antes do Python 3.14, as uniões antigas eram implementadas usando a classe " +"privada ``typing._UnionGenericAlias``. Essa classe não é mais necessária " +"para a implementação, mas foi mantida para compatibilidade com versões " +"anteriores, com remoção prevista para o Python 3.17. Os usuários devem usar " +"auxiliares de introspecção documentados, como :func:`typing.get_origin` e :" +"func:`typing.get_args`, em vez de depender de detalhes de implementação " +"privada." + +#: ../../deprecations/pending-removal-in-3.17.rst:33 +msgid "" +":class:`typing.ByteString`, deprecated since Python 3.9, is scheduled for " +"removal in Python 3.17." +msgstr "" +":class:`typing.ByteString`, obsoleto desde o Python 3.9, está programado " +"para ser removido no Python 3.17." diff --git a/deprecations/pending-removal-in-future.po b/deprecations/pending-removal-in-future.po index c316e153c..bac57a481 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 +# python-doc bot, 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-10-07 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,20 @@ 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 -msgid "``bool(NotImplemented)``." -msgstr "``bool(NotImplemented)``." - -#: ../../deprecations/pending-removal-in-future.rst:16 +#: ../../deprecations/pending-removal-in-future.rst:12 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:15 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 +78,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:23 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 +88,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:26 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 +98,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:29 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 +108,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:32 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:33 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 +124,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:38 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:43 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:46 msgid ":mod:`datetime`:" msgstr ":mod:`datetime`:" -#: ../../deprecations/pending-removal-in-future.rst:52 +#: ../../deprecations/pending-removal-in-future.rst:48 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." @@ -165,7 +153,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:50 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." @@ -173,68 +161,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:53 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:55 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:57 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:60 msgid ":mod:`importlib.metadata`:" msgstr ":mod:`importlib.metadata`:" -#: ../../deprecations/pending-removal-in-future.rst:67 +#: ../../deprecations/pending-removal-in-future.rst:62 msgid "``EntryPoints`` tuple interface." msgstr "Interface de tupla ``EntryPoints``." -#: ../../deprecations/pending-removal-in-future.rst:68 +#: ../../deprecations/pending-removal-in-future.rst:63 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:65 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:68 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:71 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:73 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:76 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 +226,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:83 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:85 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:88 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:90 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:91 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:94 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:95 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:96 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "``ssl.PROTOCOL_SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:102 +#: ../../deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_TLS``" msgstr "``ssl.PROTOCOL_TLS``" -#: ../../deprecations/pending-removal-in-future.rst:103 +#: ../../deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "``ssl.PROTOCOL_TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:104 +#: ../../deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "``ssl.PROTOCOL_TLSv1_1``" -#: ../../deprecations/pending-removal-in-future.rst:105 +#: ../../deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "``ssl.PROTOCOL_TLSv1_2``" -#: ../../deprecations/pending-removal-in-future.rst:106 +#: ../../deprecations/pending-removal-in-future.rst:101 msgid "``ssl.TLSVersion.SSLv3``" msgstr "``ssl.TLSVersion.SSLv3``" -#: ../../deprecations/pending-removal-in-future.rst:107 +#: ../../deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.TLSv1``" msgstr "``ssl.TLSVersion.TLSv1``" -#: ../../deprecations/pending-removal-in-future.rst:108 +#: ../../deprecations/pending-removal-in-future.rst:103 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:105 msgid ":mod:`threading` methods:" msgstr "Métodos de :mod:`threading`:" -#: ../../deprecations/pending-removal-in-future.rst:115 +#: ../../deprecations/pending-removal-in-future.rst:107 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." @@ -339,11 +315,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:108 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:109 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." @@ -351,7 +327,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:111 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." @@ -359,20 +335,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:113 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:114 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:116 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:118 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." @@ -380,7 +356,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:121 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" @@ -388,51 +364,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:123 msgid "``splitattr()``" msgstr "``splitattr()``" -#: ../../deprecations/pending-removal-in-future.rst:132 +#: ../../deprecations/pending-removal-in-future.rst:124 msgid "``splithost()``" msgstr "``splithost()``" -#: ../../deprecations/pending-removal-in-future.rst:133 +#: ../../deprecations/pending-removal-in-future.rst:125 msgid "``splitnport()``" msgstr "``splitnport()``" -#: ../../deprecations/pending-removal-in-future.rst:134 +#: ../../deprecations/pending-removal-in-future.rst:126 msgid "``splitpasswd()``" msgstr "``splitpasswd()``" -#: ../../deprecations/pending-removal-in-future.rst:135 +#: ../../deprecations/pending-removal-in-future.rst:127 msgid "``splitport()``" msgstr "``splitport()``" -#: ../../deprecations/pending-removal-in-future.rst:136 +#: ../../deprecations/pending-removal-in-future.rst:128 msgid "``splitquery()``" msgstr "``splitquery()``" -#: ../../deprecations/pending-removal-in-future.rst:137 +#: ../../deprecations/pending-removal-in-future.rst:129 msgid "``splittag()``" msgstr "``splittag()``" -#: ../../deprecations/pending-removal-in-future.rst:138 +#: ../../deprecations/pending-removal-in-future.rst:130 msgid "``splittype()``" msgstr "``splittype()``" -#: ../../deprecations/pending-removal-in-future.rst:139 +#: ../../deprecations/pending-removal-in-future.rst:131 msgid "``splituser()``" msgstr "``splituser()``" -#: ../../deprecations/pending-removal-in-future.rst:140 +#: ../../deprecations/pending-removal-in-future.rst:132 msgid "``splitvalue()``" msgstr "``splitvalue()``" -#: ../../deprecations/pending-removal-in-future.rst:141 +#: ../../deprecations/pending-removal-in-future.rst:133 msgid "``to_bytes()``" msgstr "``to_bytes()``" -#: ../../deprecations/pending-removal-in-future.rst:143 +#: ../../deprecations/pending-removal-in-future.rst:135 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " @@ -443,7 +419,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:139 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." @@ -451,7 +427,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:142 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 +439,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:147 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..2986789d9 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..25610739b 100644 --- a/extending/building.po +++ b/extending/building.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-25 15:05+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -62,20 +63,35 @@ msgstr "" #: ../../extending/building.rst:25 msgid "" -"For modules with ASCII-only names, the function must be named " -"``PyInit_``, with ```` replaced by the name of the " -"module. When using :ref:`multi-phase-initialization`, non-ASCII module names " -"are allowed. In this case, the initialization function name is " -"``PyInitU_``, with ```` encoded using Python's " -"*punycode* encoding with hyphens replaced by underscores. In Python::" +"For modules with ASCII-only names, the function must be named :samp:" +"`PyInit_{}`, with ```` replaced by the name of the module. When " +"using :ref:`multi-phase-initialization`, non-ASCII module names are allowed. " +"In this case, the initialization function name is :samp:`PyInitU_{}`, " +"with ```` encoded using Python's *punycode* encoding with hyphens " +"replaced by underscores. In Python::" +msgstr "" +"Para módulos com nomes com somente ASCII, a função deve ser nomeada :samp:" +"`PyInit_{}`, com ```` substituído pelo nome do módulo. Ao usar :" +"ref:`multi-phase-initialization`, nomes de módulos não ASCII são permitidos. " +"Neste caso, o nome da função de inicialização é :samp:`PyInitU_{}`, " +"com ```` codificado usando a codificação *punycode* do Python com " +"hífenes 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 "" -"Para módulos com nomes somente ASCII, a função deve ser nomeada " -"``PyInit_``, com ```` substituído pelo nome do " -"módulo. Ao usar :ref:`multi-phase-initialization`, nomes de módulos não " -"ASCII são permitidos. Neste caso, o nome da função de inicialização é " -"``PyInitU_``, com ```` codificado usando a " -"codificação *punycode* do Python com hifenes substituídos por sublinhados. " -"Em Python::" +"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 "" diff --git a/extending/embedding.po b/extending/embedding.po index 31367f2d3..081f2afbf 100644 --- a/extending/embedding.po +++ b/extending/embedding.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +40,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 +58,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 +107,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 +251,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 +336,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 +364,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 +400,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,30 +427,76 @@ msgid "" "like you would write a normal Python extension. For example::" msgstr "" -#: ../../extending/embedding.rst:265 +#: ../../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 emb_module_methods[] = {\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 struct PyModuleDef emb_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"emb\",\n" +" .m_size = 0,\n" +" .m_methods = emb_module_methods,\n" +"};\n" +"\n" +"static PyObject*\n" +"PyInit_emb(void)\n" +"{\n" +" return PyModuleDef_Init(&emb_module);\n" +"}" +msgstr "" + +#: ../../extending/embedding.rst:267 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:271 +#: ../../extending/embedding.rst:270 +msgid "" +"numargs = argc;\n" +"PyImport_AppendInittab(\"emb\", &PyInit_emb);" +msgstr "" + +#: ../../extending/embedding.rst:273 msgid "" "These two lines initialize the ``numargs`` variable, and make the :func:`!" "emb.numargs` function accessible to the embedded Python interpreter. With " "these extensions, the Python script can do things like" msgstr "" -#: ../../extending/embedding.rst:280 +#: ../../extending/embedding.rst:277 +msgid "" +"import emb\n" +"print(\"Number of arguments\", emb.numargs())" +msgstr "" + +#: ../../extending/embedding.rst:282 msgid "" "In a real application, the methods will expose an API of the application to " "Python." msgstr "" +"Em uma aplicação real, os métodos exporão uma API da aplicação para Python." -#: ../../extending/embedding.rst:290 +#: ../../extending/embedding.rst:292 msgid "Embedding Python in C++" msgstr "" -#: ../../extending/embedding.rst:292 +#: ../../extending/embedding.rst:294 msgid "" "It is also possible to embed Python in a C++ program; precisely how this is " "done will depend on the details of the C++ system used; in general you will " @@ -291,11 +505,11 @@ msgid "" "+." msgstr "" -#: ../../extending/embedding.rst:301 +#: ../../extending/embedding.rst:303 msgid "Compiling and Linking under Unix-like systems" msgstr "" -#: ../../extending/embedding.rst:303 +#: ../../extending/embedding.rst:305 msgid "" "It is not necessarily trivial to find the right flags to pass to your " "compiler (and linker) in order to embed the Python interpreter into your " @@ -303,7 +517,7 @@ msgid "" "implemented as C dynamic extensions (:file:`.so` files) linked against it." msgstr "" -#: ../../extending/embedding.rst:309 +#: ../../extending/embedding.rst:311 msgid "" "To find out the required compiler and linker flags, you can execute the :" "file:`python{X.Y}-config` script which is generated as part of the " @@ -312,19 +526,33 @@ msgid "" "directly useful to you:" msgstr "" -#: ../../extending/embedding.rst:315 +#: ../../extending/embedding.rst:317 msgid "" "``pythonX.Y-config --cflags`` will give you the recommended flags when " "compiling:" msgstr "" -#: ../../extending/embedding.rst:323 +#: ../../extending/embedding.rst:320 +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:325 msgid "" "``pythonX.Y-config --ldflags --embed`` will give you the recommended flags " "when linking:" msgstr "" -#: ../../extending/embedding.rst:332 +#: ../../extending/embedding.rst:328 +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:334 msgid "" "To avoid confusion between several Python installations (and especially " "between the system Python and your own compiled Python), it is recommended " @@ -332,7 +560,7 @@ msgid "" "above example." msgstr "" -#: ../../extending/embedding.rst:337 +#: ../../extending/embedding.rst:339 msgid "" "If this procedure doesn't work for you (it is not guaranteed to work for all " "Unix-like platforms; however, we welcome :ref:`bug reports >> 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..c2320b5cb 100644 --- a/extending/extending.po +++ b/extending/extending.po @@ -1,29 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +104,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 +126,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:706 +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 " @@ -152,22 +163,111 @@ msgstr "" #: ../../extending/extending.rst:77 msgid "" "All user-visible symbols defined by :file:`Python.h` have a prefix of ``Py`` " -"or ``PY``, except those defined in standard header files. For convenience, " -"and since they are used extensively by the Python interpreter, ``\"Python." -"h\"`` includes a few standard header files: ````, ````, " -"````, and ````. If the latter header file does not exist " -"on your system, it declares the functions :c:func:`malloc`, :c:func:`free` " -"and :c:func:`realloc` directly." +"or ``PY``, except those defined in standard header files." +msgstr "" + +#: ../../extending/extending.rst:82 +msgid "" +"For backward compatibility, :file:`Python.h` includes several standard " +"header files. C extensions should include the standard headers that they " +"use, and should not rely on these implicit includes. If using the limited C " +"API version 3.13 or newer, the implicit includes are:" +msgstr "" + +#: ../../extending/extending.rst:87 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:88 +msgid "```` (on Windows)" +msgstr "" + +#: ../../extending/extending.rst:89 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:90 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:91 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:92 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:93 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:94 +msgid "```` (if present)" +msgstr "" + +#: ../../extending/extending.rst:96 +msgid "" +"If :c:macro:`Py_LIMITED_API` is not defined, or is set to version 3.12 or " +"older, the headers below are also included:" +msgstr "" + +#: ../../extending/extending.rst:99 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:100 +msgid "```` (on POSIX)" +msgstr "" + +#: ../../extending/extending.rst:102 +msgid "" +"If :c:macro:`Py_LIMITED_API` is not defined, or is set to version 3.10 or " +"older, the headers below are also included:" +msgstr "" + +#: ../../extending/extending.rst:105 +msgid "````" msgstr "" -#: ../../extending/extending.rst:85 +#: ../../extending/extending.rst:106 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:107 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:108 +msgid "````" +msgstr "" + +#: ../../extending/extending.rst:110 msgid "" "The next thing we add to our module file is the C function that will be " "called when the Python expression ``spam.system(string)`` is evaluated " "(we'll see shortly how it ends up being called)::" msgstr "" +"A próxima coisa que adicionamos ao nosso arquivo de módulo é a função C que " +"será chamada quando a expressão Python ``spam.system(string)`` for avaliada " +"(veremos em breve como ela acaba sendo chamada)::" -#: ../../extending/extending.rst:101 +#: ../../extending/extending.rst:114 +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:126 msgid "" "There is a straightforward translation from the argument list in Python (for " "example, the single expression ``\"ls -l\"``) to the arguments passed to the " @@ -175,13 +275,15 @@ msgid "" "*self* and *args*." msgstr "" -#: ../../extending/extending.rst:106 +#: ../../extending/extending.rst:131 msgid "" "The *self* argument points to the module object for module-level functions; " "for a method it would point to the object instance." msgstr "" +"O argumento *self* aponta para o objeto do módulo para funções de nível de " +"módulo; para um método, ele apontaria para a instância do objeto." -#: ../../extending/extending.rst:109 +#: ../../extending/extending.rst:134 msgid "" "The *args* argument will be a pointer to a Python tuple object containing " "the arguments. Each item of the tuple corresponds to an argument in the " @@ -193,7 +295,7 @@ msgid "" "variables into which to store the converted values. More about this later." msgstr "" -#: ../../extending/extending.rst:118 +#: ../../extending/extending.rst:143 msgid "" ":c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the " "right type and its components have been stored in the variables whose " @@ -203,11 +305,11 @@ msgid "" "example)." msgstr "" -#: ../../extending/extending.rst:128 +#: ../../extending/extending.rst:153 msgid "Intermezzo: Errors and Exceptions" -msgstr "" +msgstr "Intermezzo: erros e exceções" -#: ../../extending/extending.rst:130 +#: ../../extending/extending.rst:155 msgid "" "An important convention throughout the Python interpreter is the following: " "when a function fails, it should set an exception condition and return an " @@ -219,13 +321,15 @@ msgid "" "important to know about them to understand how errors are passed around." msgstr "" -#: ../../extending/extending.rst:139 +#: ../../extending/extending.rst:164 msgid "" "The Python API defines a number of functions to set various types of " "exceptions." msgstr "" +"A API Python define uma série de funções para definir vários tipos de " +"exceções." -#: ../../extending/extending.rst:141 +#: ../../extending/extending.rst:166 msgid "" "The most common one is :c:func:`PyErr_SetString`. Its arguments are an " "exception object and a C string. The exception object is usually a " @@ -234,7 +338,7 @@ msgid "" "and stored as the \"associated value\" of the exception." msgstr "" -#: ../../extending/extending.rst:147 +#: ../../extending/extending.rst:172 msgid "" "Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an " "exception argument and constructs the associated value by inspection of the " @@ -244,7 +348,7 @@ msgid "" "to any of these functions." msgstr "" -#: ../../extending/extending.rst:154 +#: ../../extending/extending.rst:179 msgid "" "You can test non-destructively whether an exception has been set with :c:" "func:`PyErr_Occurred`. This returns the current exception object, or " @@ -253,7 +357,7 @@ msgid "" "since you should be able to tell from the return value." msgstr "" -#: ../../extending/extending.rst:160 +#: ../../extending/extending.rst:185 msgid "" "When a function *f* that calls another function *g* detects that the latter " "fails, *f* should itself return an error value (usually ``NULL`` or " @@ -266,7 +370,7 @@ msgid "" "tries to find an exception handler specified by the Python programmer." msgstr "" -#: ../../extending/extending.rst:170 +#: ../../extending/extending.rst:195 msgid "" "(There are situations where a module can actually give a more detailed error " "message by calling another ``PyErr_*`` function, and in such cases it is " @@ -275,7 +379,7 @@ msgid "" "can fail for a variety of reasons.)" msgstr "" -#: ../../extending/extending.rst:176 +#: ../../extending/extending.rst:201 msgid "" "To ignore an exception set by a function call that failed, the exception " "condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The " @@ -284,7 +388,7 @@ msgid "" "itself (possibly by trying something else, or pretending nothing went wrong)." msgstr "" -#: ../../extending/extending.rst:182 +#: ../../extending/extending.rst:207 msgid "" "Every failing :c:func:`malloc` call must be turned into an exception --- the " "direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call :c:func:" @@ -293,7 +397,7 @@ msgid "" "so this note is only relevant to those who call :c:func:`malloc` directly." msgstr "" -#: ../../extending/extending.rst:188 +#: ../../extending/extending.rst:213 msgid "" "Also note that, with the important exception of :c:func:`PyArg_ParseTuple` " "and friends, functions that return an integer status usually return a " @@ -301,14 +405,14 @@ msgid "" "calls." msgstr "" -#: ../../extending/extending.rst:192 +#: ../../extending/extending.rst:217 msgid "" "Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or :" "c:func:`Py_DECREF` calls for objects you have already created) when you " "return an error indicator!" msgstr "" -#: ../../extending/extending.rst:196 +#: ../../extending/extending.rst:221 msgid "" "The choice of which exception to raise is entirely yours. There are " "predeclared C objects corresponding to all built-in Python exceptions, such " @@ -321,19 +425,80 @@ msgid "" "satisfy other conditions, :c:data:`PyExc_ValueError` is appropriate." msgstr "" -#: ../../extending/extending.rst:206 +#: ../../extending/extending.rst:231 +msgid "" +"You can also define a new exception that is unique to your module. The " +"simplest way to do this is to declare a static global object variable at the " +"beginning of the file::" +msgstr "" + +#: ../../extending/extending.rst:235 +msgid "static PyObject *SpamError = NULL;" +msgstr "" + +#: ../../extending/extending.rst:237 msgid "" -"You can also define a new exception that is unique to your module. For this, " -"you usually declare a static object variable at the beginning of your file::" +"and initialize it by calling :c:func:`PyErr_NewException` in the module's :c:" +"data:`Py_mod_exec` function (:c:func:`!spam_module_exec`)::" msgstr "" -#: ../../extending/extending.rst:211 +#: ../../extending/extending.rst:240 +msgid "SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);" +msgstr "" + +#: ../../extending/extending.rst:242 msgid "" -"and initialize it in your module's initialization function (:c:func:`!" -"PyInit_spam`) with an exception object::" +"Since :c:data:`!SpamError` is a global variable, it will be overwritten " +"every time the module is reinitialized, when the :c:data:`Py_mod_exec` " +"function is called." msgstr "" -#: ../../extending/extending.rst:233 +#: ../../extending/extending.rst:245 +msgid "" +"For now, let's avoid the issue: we will block repeated initialization by " +"raising an :py:exc:`ImportError`::" +msgstr "" + +#: ../../extending/extending.rst:248 +msgid "" +"static PyObject *SpamError = NULL;\n" +"\n" +"static int\n" +"spam_module_exec(PyObject *m)\n" +"{\n" +" if (SpamError != NULL) {\n" +" PyErr_SetString(PyExc_ImportError,\n" +" \"cannot initialize spam module more than once\");\n" +" return -1;\n" +" }\n" +" SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\n" +" if (PyModule_AddObjectRef(m, \"SpamError\", SpamError) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot spam_module_slots[] = {\n" +" {Py_mod_exec, spam_module_exec},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static struct PyModuleDef spam_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" .m_size = 0, // non-negative\n" +" .m_slots = spam_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModuleDef_Init(&spam_module);\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:284 msgid "" "Note that the Python name for the exception object is :exc:`!spam.error`. " "The :c:func:`PyErr_NewException` function may create a class with the base " @@ -341,7 +506,7 @@ msgid "" "``NULL``), described in :ref:`bltin-exceptions`." msgstr "" -#: ../../extending/extending.rst:238 +#: ../../extending/extending.rst:289 msgid "" "Note also that the :c:data:`!SpamError` variable retains a reference to the " "newly created exception class; this is intentional! Since the exception " @@ -352,29 +517,62 @@ msgid "" "unintended side effects." msgstr "" -#: ../../extending/extending.rst:245 +#: ../../extending/extending.rst:296 +msgid "" +"For now, the :c:func:`Py_DECREF` call to remove this reference is missing. " +"Even when the Python interpreter shuts down, the global :c:data:`!SpamError` " +"variable will not be garbage-collected. It will \"leak\". We did, however, " +"ensure that this will happen at most once per process." +msgstr "" + +#: ../../extending/extending.rst:301 msgid "" "We discuss the use of :c:macro:`PyMODINIT_FUNC` as a function return type " "later in this sample." msgstr "" -#: ../../extending/extending.rst:248 +#: ../../extending/extending.rst:304 msgid "" "The :exc:`!spam.error` exception can be raised in your extension module " "using a call to :c:func:`PyErr_SetString` as shown below::" msgstr "" -#: ../../extending/extending.rst:271 -msgid "Back to the Example" +#: ../../extending/extending.rst:307 +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:273 +#: ../../extending/extending.rst:327 +msgid "Back to the Example" +msgstr "De volta ao exemplo" + +#: ../../extending/extending.rst:329 msgid "" "Going back to our example function, you should now be able to understand " "this statement::" msgstr "" -#: ../../extending/extending.rst:279 +#: ../../extending/extending.rst:332 +msgid "" +"if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;" +msgstr "" + +#: ../../extending/extending.rst:335 msgid "" "It returns ``NULL`` (the error indicator for functions returning object " "pointers) if an error is detected in the argument list, relying on the " @@ -385,26 +583,36 @@ msgid "" "properly be declared as ``const char *command``)." msgstr "" -#: ../../extending/extending.rst:287 +#: ../../extending/extending.rst:343 msgid "" "The next statement is a call to the Unix function :c:func:`system`, passing " "it the string we just got from :c:func:`PyArg_ParseTuple`::" msgstr "" -#: ../../extending/extending.rst:292 +#: ../../extending/extending.rst:346 +msgid "sts = system(command);" +msgstr "" + +#: ../../extending/extending.rst:348 msgid "" "Our :func:`!spam.system` function must return the value of :c:data:`!sts` as " "a Python object. This is done using the function :c:func:" "`PyLong_FromLong`. ::" msgstr "" -#: ../../extending/extending.rst:297 +#: ../../extending/extending.rst:351 +msgid "return PyLong_FromLong(sts);" +msgstr "" + +#: ../../extending/extending.rst:353 msgid "" "In this case, it will return an integer object. (Yes, even integers are " "objects on the heap in Python!)" msgstr "" +"Neste caso, ele retornará um objeto inteiro (sim, até mesmo inteiros são " +"objetos no heap em Python!)" -#: ../../extending/extending.rst:300 +#: ../../extending/extending.rst:356 msgid "" "If you have a C function that returns no useful argument (a function " "returning :c:expr:`void`), the corresponding Python function must return " @@ -412,24 +620,41 @@ msgid "" "macro:`Py_RETURN_NONE` macro)::" msgstr "" -#: ../../extending/extending.rst:308 +#: ../../extending/extending.rst:361 +msgid "" +"Py_INCREF(Py_None);\n" +"return Py_None;" +msgstr "" + +#: ../../extending/extending.rst:364 msgid "" ":c:data:`Py_None` is the C name for the special Python object ``None``. It " "is a genuine Python object rather than a ``NULL`` pointer, which means " "\"error\" in most contexts, as we have seen." msgstr "" -#: ../../extending/extending.rst:316 +#: ../../extending/extending.rst:372 msgid "The Module's Method Table and Initialization Function" -msgstr "" +msgstr "A tabela de métodos e a função de inicialização do módulo" -#: ../../extending/extending.rst:318 +#: ../../extending/extending.rst:374 msgid "" "I promised to show how :c:func:`!spam_system` is called from Python " "programs. First, we need to list its name and address in a \"method table\"::" msgstr "" -#: ../../extending/extending.rst:329 +#: ../../extending/extending.rst:377 +msgid "" +"static PyMethodDef spam_methods[] = {\n" +" ...\n" +" {\"system\", spam_system, METH_VARARGS,\n" +" \"Execute a shell command.\"},\n" +" ...\n" +" {NULL, NULL, 0, NULL} /* Sentinel */\n" +"};" +msgstr "" + +#: ../../extending/extending.rst:385 msgid "" "Note the third entry (``METH_VARARGS``). This is a flag telling the " "interpreter the calling convention to be used for the C function. It should " @@ -438,14 +663,14 @@ msgid "" "is used." msgstr "" -#: ../../extending/extending.rst:334 +#: ../../extending/extending.rst:390 msgid "" "When using only ``METH_VARARGS``, the function should expect the Python-" "level parameters to be passed in as a tuple acceptable for parsing via :c:" "func:`PyArg_ParseTuple`; more information on this function is provided below." msgstr "" -#: ../../extending/extending.rst:338 +#: ../../extending/extending.rst:394 msgid "" "The :c:macro:`METH_KEYWORDS` bit may be set in the third field if keyword " "arguments should be passed to the function. In this case, the C function " @@ -454,12 +679,23 @@ msgid "" "to such a function." msgstr "" -#: ../../extending/extending.rst:344 +#: ../../extending/extending.rst:400 msgid "" "The method table must be referenced in the module definition structure::" msgstr "" +"A tabela de métodos deve ser referenciada na estrutura de definição do " +"módulo::" + +#: ../../extending/extending.rst:402 +msgid "" +"static struct PyModuleDef spam_module = {\n" +" ...\n" +" .m_methods = spam_methods,\n" +" ...\n" +"};" +msgstr "" -#: ../../extending/extending.rst:355 +#: ../../extending/extending.rst:408 msgid "" "This structure, in turn, must be passed to the interpreter in the module's " "initialization function. The initialization function must be named :c:func:" @@ -467,64 +703,116 @@ msgid "" "only non-\\ ``static`` item defined in the module file::" msgstr "" -#: ../../extending/extending.rst:366 +#: ../../extending/extending.rst:413 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModuleDef_Init(&spam_module);\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:419 msgid "" "Note that :c:macro:`PyMODINIT_FUNC` declares the function as ``PyObject *`` " "return type, declares any special linkage declarations required by the " "platform, and for C++ declares the function as ``extern \"C\"``." msgstr "" -#: ../../extending/extending.rst:370 +#: ../../extending/extending.rst:423 msgid "" -"When the Python program imports module :mod:`!spam` for the first time, :c:" -"func:`!PyInit_spam` is called. (See below for comments about embedding " -"Python.) It calls :c:func:`PyModule_Create`, which returns a module object, " -"and inserts built-in function objects into the newly created module based " -"upon the table (an array of :c:type:`PyMethodDef` structures) found in the " -"module definition. :c:func:`PyModule_Create` returns a pointer to the module " -"object that it creates. It may abort with a fatal error for certain errors, " -"or return ``NULL`` if the module could not be initialized satisfactorily. " -"The init function must return the module object to its caller, so that it " -"then gets inserted into ``sys.modules``." +":c:func:`!PyInit_spam` is called when each interpreter imports its module :" +"mod:`!spam` for the first time. (See below for comments about embedding " +"Python.) A pointer to the module definition must be returned via :c:func:" +"`PyModuleDef_Init`, so that the import machinery can create the module and " +"store it in ``sys.modules``." msgstr "" -#: ../../extending/extending.rst:381 +#: ../../extending/extending.rst:428 msgid "" "When embedding Python, the :c:func:`!PyInit_spam` function is not called " -"automatically unless there's an entry in the :c:data:`PyImport_Inittab` " +"automatically unless there's an entry in the :c:data:`!PyImport_Inittab` " "table. To add the module to the initialization table, use :c:func:" "`PyImport_AppendInittab`, optionally followed by an import of the module::" msgstr "" -#: ../../extending/extending.rst:436 +#: ../../extending/extending.rst:433 +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:483 msgid "" -"Removing entries from ``sys.modules`` or importing compiled modules into " +"If you declare a global variable or a local static one, the module may " +"experience unintended side-effects on re-initialisation, for example when " +"removing entries from ``sys.modules`` or importing compiled modules into " "multiple interpreters within a process (or following a :c:func:`fork` " -"without an intervening :c:func:`exec`) can create problems for some " -"extension modules. Extension module authors should exercise caution when " -"initializing internal data structures." +"without an intervening :c:func:`exec`). If module state is not yet fully :" +"ref:`isolated `, authors should consider marking " +"the module as having no support for subinterpreters (via :c:macro:" +"`Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED`)." msgstr "" -#: ../../extending/extending.rst:442 +#: ../../extending/extending.rst:492 msgid "" "A more substantial example module is included in the Python source " -"distribution as :file:`Modules/xxmodule.c`. This file may be used as a " +"distribution as :file:`Modules/xxlimited.c`. This file may be used as a " "template or simply read as an example." msgstr "" -#: ../../extending/extending.rst:448 -msgid "" -"Unlike our ``spam`` example, ``xxmodule`` uses *multi-phase initialization* " -"(new in Python 3.5), where a PyModuleDef structure is returned from " -"``PyInit_spam``, and creation of the module is left to the import machinery. " -"For details on multi-phase initialization, see :PEP:`489`." -msgstr "" - -#: ../../extending/extending.rst:457 +#: ../../extending/extending.rst:500 msgid "Compilation and Linkage" -msgstr "" +msgstr "Compilação e vinculação" -#: ../../extending/extending.rst:459 +#: ../../extending/extending.rst:502 msgid "" "There are two more things to do before you can use your new extension: " "compiling and linking it with the Python system. If you use dynamic " @@ -533,8 +821,15 @@ msgid "" "`building`) and additional information that pertains only to building on " "Windows (chapter :ref:`building-on-windows`) for more information about this." msgstr "" +"Há mais duas coisas a fazer antes de usar sua nova extensão: compilá-la e " +"vinculá-la ao sistema Python. Se você usa carregamento dinâmico, os detalhes " +"podem depender do estilo de carregamento dinâmico que seu sistema utiliza; " +"consulte os capítulos sobre construção de módulos de extensão (capítulo :ref:" +"`building`) e informações adicionais referentes apenas à construção no " +"Windows (capítulo :ref:`building-on-windows`) para obter mais informações " +"sobre isso." -#: ../../extending/extending.rst:466 +#: ../../extending/extending.rst:509 msgid "" "If you can't use dynamic loading, or if you want to make your module a " "permanent part of the Python interpreter, you will have to change the " @@ -544,7 +839,11 @@ msgid "" "line to the file :file:`Modules/Setup.local` describing your file:" msgstr "" -#: ../../extending/extending.rst:477 +#: ../../extending/extending.rst:516 +msgid "spam spammodule.o" +msgstr "" + +#: ../../extending/extending.rst:520 msgid "" "and rebuild the interpreter by running :program:`make` in the toplevel " "directory. You can also run :program:`make` in the :file:`Modules/` " @@ -553,17 +852,21 @@ msgid "" "the :file:`Setup` file.)" msgstr "" -#: ../../extending/extending.rst:483 +#: ../../extending/extending.rst:526 msgid "" "If your module requires additional libraries to link with, these can be " "listed on the line in the configuration file as well, for instance:" msgstr "" -#: ../../extending/extending.rst:494 -msgid "Calling Python Functions from C" +#: ../../extending/extending.rst:529 +msgid "spam spammodule.o -lX11" msgstr "" -#: ../../extending/extending.rst:496 +#: ../../extending/extending.rst:537 +msgid "Calling Python Functions from C" +msgstr "Chamando funções Python de C" + +#: ../../extending/extending.rst:539 msgid "" "So far we have concentrated on making C functions callable from Python. The " "reverse is also useful: calling Python functions from C. This is especially " @@ -573,8 +876,16 @@ msgid "" "will require calling the Python callback functions from a C callback. Other " "uses are also imaginable." msgstr "" +"Até agora, nos concentramos em tornar funções C chamáveis a partir de " +"Python. O inverso também é útil: chamar funções Python a partir de C. Isso é " +"especialmente verdadeiro para bibliotecas que oferecem suporte às chamadas " +"funções de \"callback\". Se uma interface C utiliza callbacks, o Python " +"equivalente frequentemente precisa fornecer um mecanismo de callback ao " +"programador Python; a implementação exigirá a chamada das funções de " +"callback Python a partir de um callback C. Outros usos também são " +"imagináveis." -#: ../../extending/extending.rst:504 +#: ../../extending/extending.rst:547 msgid "" "Fortunately, the Python interpreter is easily called recursively, and there " "is a standard interface to call a Python function. (I won't dwell on how to " @@ -582,8 +893,14 @@ msgid "" "interested, have a look at the implementation of the :option:`-c` command " "line option in :file:`Modules/main.c` from the Python source code.)" msgstr "" +"Felizmente, o interpretador Python é facilmente chamado recursivamente, e há " +"uma interface padrão para chamar uma função Python. (Não vou me aprofundar " +"em como chamar o analisador sintático do Python com uma string específica " +"como entrada --- se você estiver interessado, dê uma olhada na implementação " +"da opção de linha de comando :option:`-c` em :file:`Modules/main.c` do " +"código-fonte Python.)" -#: ../../extending/extending.rst:510 +#: ../../extending/extending.rst:553 msgid "" "Calling a Python function is easy. First, the Python program must somehow " "pass you the Python function object. You should provide a function (or some " @@ -593,7 +910,34 @@ msgid "" "function might be part of a module definition::" msgstr "" -#: ../../extending/extending.rst:540 +#: ../../extending/extending.rst:560 +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:583 msgid "" "This function must be registered with the interpreter using the :c:macro:" "`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The :" @@ -601,7 +945,7 @@ msgid "" "section :ref:`parsetuple`." msgstr "" -#: ../../extending/extending.rst:545 +#: ../../extending/extending.rst:588 msgid "" "The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement " "the reference count of an object and are safe in the presence of ``NULL`` " @@ -609,7 +953,7 @@ msgid "" "info on them in section :ref:`refcounts`." msgstr "" -#: ../../extending/extending.rst:552 +#: ../../extending/extending.rst:595 msgid "" "Later, when it is time to call the function, you call the C function :c:func:" "`PyObject_CallObject`. This function has two arguments, both pointers to " @@ -621,7 +965,21 @@ msgid "" "or more format codes between parentheses. For example::" msgstr "" -#: ../../extending/extending.rst:572 +#: ../../extending/extending.rst:604 +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:615 msgid "" ":c:func:`PyObject_CallObject` returns a Python object pointer: this is the " "return value of the Python function. :c:func:`PyObject_CallObject` is " @@ -630,7 +988,7 @@ msgid "" "`Py_DECREF`\\ -ed immediately after the :c:func:`PyObject_CallObject` call." msgstr "" -#: ../../extending/extending.rst:579 +#: ../../extending/extending.rst:622 msgid "" "The return value of :c:func:`PyObject_CallObject` is \"new\": either it is a " "brand new object, or it is an existing object whose reference count has been " @@ -639,7 +997,7 @@ msgid "" "not interested in its value." msgstr "" -#: ../../extending/extending.rst:585 +#: ../../extending/extending.rst:628 msgid "" "Before you do this, however, it is important to check that the return value " "isn't ``NULL``. If it is, the Python function terminated by raising an " @@ -650,7 +1008,15 @@ msgid "" "should be cleared by calling :c:func:`PyErr_Clear`. For example::" msgstr "" -#: ../../extending/extending.rst:598 +#: ../../extending/extending.rst:636 +msgid "" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"...use result...\n" +"Py_DECREF(result);" +msgstr "" + +#: ../../extending/extending.rst:641 msgid "" "Depending on the desired interface to the Python callback function, you may " "also have to provide an argument list to :c:func:`PyObject_CallObject`. In " @@ -662,7 +1028,20 @@ msgid "" "you want to pass an integral event code, you might use the following code::" msgstr "" -#: ../../extending/extending.rst:617 +#: ../../extending/extending.rst:650 +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:660 msgid "" "Note the placement of ``Py_DECREF(arglist)`` immediately after the call, " "before the error check! Also note that strictly speaking this code is not " @@ -670,22 +1049,39 @@ msgid "" "checked." msgstr "" -#: ../../extending/extending.rst:621 +#: ../../extending/extending.rst:664 msgid "" "You may also call a function with keyword arguments by using :c:func:" "`PyObject_Call`, which supports arguments and keyword arguments. As in the " "above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::" msgstr "" -#: ../../extending/extending.rst:639 -msgid "Extracting Parameters in Extension Functions" +#: ../../extending/extending.rst:668 +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:643 +#: ../../extending/extending.rst:682 +msgid "Extracting Parameters in Extension Functions" +msgstr "Extraindo parâmetros em funções de extensão" + +#: ../../extending/extending.rst:686 msgid "The :c:func:`PyArg_ParseTuple` function is declared as follows::" msgstr "" -#: ../../extending/extending.rst:647 +#: ../../extending/extending.rst:688 +msgid "int PyArg_ParseTuple(PyObject *arg, const char *format, ...);" +msgstr "" + +#: ../../extending/extending.rst:690 msgid "" "The *arg* argument must be a tuple object containing an argument list passed " "from Python to a C function. The *format* argument must be a format string, " @@ -693,8 +1089,13 @@ msgid "" "Reference Manual. The remaining arguments must be addresses of variables " "whose type is determined by the format string." msgstr "" +"O argumento *arg* deve ser um objeto tupla contendo uma lista de argumentos " +"passada de Python para uma função C. O argumento *format* deve ser uma " +"string de formato, cuja sintaxe é explicada em :ref:`arg-parsing` no Manual " +"de Referência da API C/Python. Os argumentos restantes devem ser endereços " +"de variáveis cujo tipo é determinado pela string de formato." -#: ../../extending/extending.rst:653 +#: ../../extending/extending.rst:696 msgid "" "Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments " "have the required types, it cannot check the validity of the addresses of C " @@ -702,7 +1103,7 @@ msgid "" "probably crash or at least overwrite random bits in memory. So be careful!" msgstr "" -#: ../../extending/extending.rst:658 +#: ../../extending/extending.rst:701 msgid "" "Note that any Python object references which are provided to the caller are " "*borrowed* references; do not decrement their reference count!" @@ -711,20 +1112,96 @@ msgstr "" "chamador são referências *emprestadas*; não decremente a contagem de " "referências delas!" -#: ../../extending/extending.rst:661 +#: ../../extending/extending.rst:704 msgid "Some example calls::" +msgstr "Alguns exemplos de chamadas::" + +#: ../../extending/extending.rst:711 +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:731 -msgid "Keyword Parameters for Extension Functions" +#: ../../extending/extending.rst:722 +msgid "" +"ok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n" +" /* Possible Python call: f('whoops!') */" +msgstr "" + +#: ../../extending/extending.rst:727 +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:732 +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:738 +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:752 +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:763 +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:735 +#: ../../extending/extending.rst:774 +msgid "Keyword Parameters for Extension Functions" +msgstr "Parâmetros nomeados para funções de extensão" + +#: ../../extending/extending.rst:778 msgid "" "The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::" msgstr "" -#: ../../extending/extending.rst:740 +#: ../../extending/extending.rst:780 +msgid "" +"int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,\n" +" const char *format, char * const " +"*kwlist, ...);" +msgstr "" + +#: ../../extending/extending.rst:783 msgid "" "The *arg* and *format* parameters are identical to those of the :c:func:" "`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of " @@ -736,30 +1213,89 @@ msgid "" "raises an appropriate exception." msgstr "" -#: ../../extending/extending.rst:750 +#: ../../extending/extending.rst:793 msgid "" "Nested tuples cannot be parsed when using keyword arguments! Keyword " "parameters passed in which are not present in the *kwlist* will cause :exc:" "`TypeError` to be raised." msgstr "" -#: ../../extending/extending.rst:756 +#: ../../extending/extending.rst:799 msgid "" "Here is an example module which uses keywords, based on an example by Geoff " "Philbrick (philbrick@hks.com)::" msgstr "" - -#: ../../extending/extending.rst:811 +"Aqui está um módulo de exemplo que usa parâmetros nomeados, baseado em um " +"exemplo de Geoff Philbrick (philbrick@hks.com)::" + +#: ../../extending/extending.rst:802 +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 keywdarg_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"keywdarg\",\n" +" .m_size = 0,\n" +" .m_methods = keywdarg_methods,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_keywdarg(void)\n" +"{\n" +" return PyModuleDef_Init(&keywdarg_module);\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:853 msgid "Building Arbitrary Values" -msgstr "" +msgstr "Construindo valores arbitrários" -#: ../../extending/extending.rst:813 +#: ../../extending/extending.rst:855 msgid "" "This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is " "declared as follows::" msgstr "" -#: ../../extending/extending.rst:818 +#: ../../extending/extending.rst:858 +msgid "PyObject *Py_BuildValue(const char *format, ...);" +msgstr "" + +#: ../../extending/extending.rst:860 msgid "" "It recognizes a set of format units similar to the ones recognized by :c:" "func:`PyArg_ParseTuple`, but the arguments (which are input to the function, " @@ -767,7 +1303,7 @@ msgid "" "object, suitable for returning from a C function called from Python." msgstr "" -#: ../../extending/extending.rst:823 +#: ../../extending/extending.rst:865 msgid "" "One difference with :c:func:`PyArg_ParseTuple`: while the latter requires " "its first argument to be a tuple (since Python argument lists are always " @@ -779,16 +1315,37 @@ msgid "" "parenthesize the format string." msgstr "" -#: ../../extending/extending.rst:831 +#: ../../extending/extending.rst:873 msgid "" "Examples (to the left the call, to the right the resulting Python value):" msgstr "" -#: ../../extending/extending.rst:857 +#: ../../extending/extending.rst:875 +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:899 msgid "Reference Counts" msgstr "Contagens de referências" -#: ../../extending/extending.rst:859 +#: ../../extending/extending.rst:901 msgid "" "In languages like C or C++, the programmer is responsible for dynamic " "allocation and deallocation of memory on the heap. In C, this is done using " @@ -797,7 +1354,7 @@ msgid "" "restrict the following discussion to the C case." msgstr "" -#: ../../extending/extending.rst:865 +#: ../../extending/extending.rst:907 msgid "" "Every block of memory allocated with :c:func:`malloc` should eventually be " "returned to the pool of available memory by exactly one call to :c:func:" @@ -812,7 +1369,7 @@ msgid "" "crashes." msgstr "" -#: ../../extending/extending.rst:876 +#: ../../extending/extending.rst:918 msgid "" "Common causes of memory leaks are unusual paths through the code. For " "instance, a function may allocate a block of memory, do some calculation, " @@ -828,8 +1385,22 @@ msgid "" "happening by having a coding convention or strategy that minimizes this kind " "of errors." msgstr "" +"Causas comuns de vazamentos de memória são caminhos incomuns no código. Por " +"exemplo, uma função pode alocar um bloco de memória, executar algum cálculo " +"e, em seguida, liberar o bloco novamente. Agora, uma alteração nos " +"requisitos da função pode adicionar um teste ao cálculo que detecta uma " +"condição de erro e pode retornar prematuramente da função. É fácil esquecer " +"de liberar o bloco de memória alocado ao executar essa saída prematura, " +"especialmente quando ela é adicionada posteriormente ao código. Esses " +"vazamentos, uma vez introduzidos, geralmente passam despercebidos por um " +"longo tempo: a saída de erro é executada apenas em uma pequena fração de " +"todas as chamadas, e a maioria das máquinas modernas tem bastante memória " +"virtual, portanto, o vazamento só se torna aparente em um processo de longa " +"duração que usa a função com vazamento com frequência. Portanto, é " +"importante evitar que vazamentos aconteçam por meio de uma convenção ou " +"estratégia de codificação que minimize esse tipo de erro." -#: ../../extending/extending.rst:889 +#: ../../extending/extending.rst:931 msgid "" "Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it " "needs a strategy to avoid memory leaks as well as the use of freed memory. " @@ -840,7 +1411,7 @@ msgid "" "reference to the object has been deleted and the object is freed." msgstr "" -#: ../../extending/extending.rst:897 +#: ../../extending/extending.rst:939 msgid "" "An alternative strategy is called :dfn:`automatic garbage collection`. " "(Sometimes, reference counting is also referred to as a garbage collection " @@ -856,7 +1427,7 @@ msgid "" "with reference counts." msgstr "" -#: ../../extending/extending.rst:909 +#: ../../extending/extending.rst:951 msgid "" "While Python uses the traditional reference counting implementation, it also " "offers a cycle detector that works to detect reference cycles. This allows " @@ -869,8 +1440,20 @@ msgid "" "in a reference cycle, or referenced from the objects in the cycle, even " "though there are no further references to the cycle itself." msgstr "" - -#: ../../extending/extending.rst:920 +"Embora o Python utilize a implementação tradicional de contagem de " +"referências, ele também oferece um detector de ciclos que funciona para " +"detectar ciclos de referência. Isso permite que as aplicações não se " +"preocupem em criar referências circulares diretas ou indiretas; esses são os " +"pontos fracos da coleta de lixo implementada usando apenas a contagem de " +"referências. Ciclos de referência consistem em objetos que contêm " +"referências (possivelmente indiretas) a si mesmos, de modo que cada objeto " +"no ciclo tem uma contagem de referências diferente de zero. Implementações " +"típicas de contagem de referências não são capazes de recuperar a memória " +"pertencente a nenhum objeto em um ciclo de referência, ou referenciada a " +"partir dos objetos no ciclo, mesmo que não haja mais referências ao próprio " +"ciclo." + +#: ../../extending/extending.rst:962 msgid "" "The cycle detector is able to detect garbage cycles and can reclaim them. " "The :mod:`gc` module exposes a way to run the detector (the :func:`~gc." @@ -878,11 +1461,11 @@ msgid "" "disable the detector at runtime." msgstr "" -#: ../../extending/extending.rst:929 +#: ../../extending/extending.rst:971 msgid "Reference Counting in Python" -msgstr "" +msgstr "Contagem de referências no Python" -#: ../../extending/extending.rst:931 +#: ../../extending/extending.rst:973 msgid "" "There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle " "the incrementing and decrementing of the reference count. :c:func:" @@ -893,7 +1476,7 @@ msgid "" "object." msgstr "" -#: ../../extending/extending.rst:938 +#: ../../extending/extending.rst:980 msgid "" "The big question now remains: when to use ``Py_INCREF(x)`` and " "``Py_DECREF(x)``? Let's first introduce some terms. Nobody \"owns\" an " @@ -906,7 +1489,7 @@ msgid "" "reference creates a memory leak." msgstr "" -#: ../../extending/extending.rst:947 +#: ../../extending/extending.rst:989 msgid "" "It is also possible to :dfn:`borrow` [#]_ a reference to an object. The " "borrower of a reference should not call :c:func:`Py_DECREF`. The borrower " @@ -915,7 +1498,7 @@ msgid "" "risks using freed memory and should be avoided completely [#]_." msgstr "" -#: ../../extending/extending.rst:953 +#: ../../extending/extending.rst:995 msgid "" "The advantage of borrowing over owning a reference is that you don't need to " "take care of disposing of the reference on all possible paths through the " @@ -926,7 +1509,7 @@ msgid "" "borrowed has in fact disposed of it." msgstr "" -#: ../../extending/extending.rst:961 +#: ../../extending/extending.rst:1003 msgid "" "A borrowed reference can be changed into an owned reference by calling :c:" "func:`Py_INCREF`. This does not affect the status of the owner from which " @@ -935,18 +1518,21 @@ msgid "" "properly, as well as the previous owner)." msgstr "" -#: ../../extending/extending.rst:971 +#: ../../extending/extending.rst:1013 msgid "Ownership Rules" -msgstr "" +msgstr "Regras de propriedade" -#: ../../extending/extending.rst:973 +#: ../../extending/extending.rst:1015 msgid "" "Whenever an object reference is passed into or out of a function, it is part " "of the function's interface specification whether ownership is transferred " "with the reference or not." msgstr "" +"Sempre que uma referência de objeto é passada para dentro ou para fora de " +"uma função, faz parte da especificação da interface da função se a " +"propriedade é transferida com a referência ou não." -#: ../../extending/extending.rst:977 +#: ../../extending/extending.rst:1019 msgid "" "Most functions that return a reference to an object pass on ownership with " "the reference. In particular, all functions whose function it is to create " @@ -957,7 +1543,7 @@ msgid "" "reference to a cached item." msgstr "" -#: ../../extending/extending.rst:985 +#: ../../extending/extending.rst:1027 msgid "" "Many functions that extract objects from other objects also transfer " "ownership with the reference, for instance :c:func:" @@ -968,14 +1554,14 @@ msgid "" "list or dictionary." msgstr "" -#: ../../extending/extending.rst:992 +#: ../../extending/extending.rst:1034 msgid "" "The function :c:func:`PyImport_AddModule` also returns a borrowed reference, " "even though it may actually create the object it returns: this is possible " "because an owned reference to the object is stored in ``sys.modules``." msgstr "" -#: ../../extending/extending.rst:996 +#: ../../extending/extending.rst:1038 msgid "" "When you pass an object reference into another function, in general, the " "function borrows the reference from you --- if it needs to store it, it will " @@ -986,7 +1572,7 @@ msgid "" "don't take over ownership --- they are \"normal.\")" msgstr "" -#: ../../extending/extending.rst:1004 +#: ../../extending/extending.rst:1046 msgid "" "When a C function is called from Python, it borrows references to its " "arguments from the caller. The caller owns a reference to the object, so " @@ -995,18 +1581,21 @@ msgid "" "turned into an owned reference by calling :c:func:`Py_INCREF`." msgstr "" -#: ../../extending/extending.rst:1010 +#: ../../extending/extending.rst:1052 msgid "" "The object reference returned from a C function that is called from Python " "must be an owned reference --- ownership is transferred from the function to " "its caller." msgstr "" +"A referência de objeto retornada de uma função C chamada do Python deve ser " +"uma referência própria --- a propriedade é transferida da função para seu " +"chamador." -#: ../../extending/extending.rst:1018 +#: ../../extending/extending.rst:1060 msgid "Thin Ice" -msgstr "" +msgstr "Gelo fino" -#: ../../extending/extending.rst:1020 +#: ../../extending/extending.rst:1062 msgid "" "There are a few situations where seemingly harmless use of a borrowed " "reference can lead to problems. These all have to do with implicit " @@ -1014,31 +1603,53 @@ msgid "" "dispose of it." msgstr "" -#: ../../extending/extending.rst:1024 +#: ../../extending/extending.rst:1066 msgid "" "The first and most important case to know about is using :c:func:`Py_DECREF` " "on an unrelated object while borrowing a reference to a list item. For " "instance::" msgstr "" -#: ../../extending/extending.rst:1036 +#: ../../extending/extending.rst:1069 +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:1078 msgid "" "This function first borrows a reference to ``list[0]``, then replaces " "``list[1]`` with the value ``0``, and finally prints the borrowed reference. " "Looks harmless, right? But it's not!" msgstr "" +"Esta função primeiro toma emprestada uma referência a ``list[0]``, depois " +"substitui ``list[1]`` pelo valor ``0`` e, por fim, imprime a referência " +"emprestada. Parece inofensivo, certo? Mas não é!" -#: ../../extending/extending.rst:1040 +#: ../../extending/extending.rst:1082 msgid "" "Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns " "references to all its items, so when item 1 is replaced, it has to dispose " "of the original item 1. Now let's suppose the original item 1 was an " "instance of a user-defined class, and let's further suppose that the class " "defined a :meth:`!__del__` method. If this class instance has a reference " -"count of 1, disposing of it will call its :meth:`!__del__` method." +"count of 1, disposing of it will call its :meth:`!__del__` method. " +"Internally, :c:func:`PyList_SetItem` calls :c:func:`Py_DECREF` on the " +"replaced item, which invokes replaced item's corresponding :c:member:" +"`~PyTypeObject.tp_dealloc` function. During deallocation, :c:member:" +"`~PyTypeObject.tp_dealloc` calls :c:member:`~PyTypeObject.tp_finalize`, " +"which is mapped to the :meth:`!__del__` method for class instances (see :pep:" +"`442`). This entire sequence happens synchronously within the :c:func:" +"`PyList_SetItem` call." msgstr "" -#: ../../extending/extending.rst:1047 +#: ../../extending/extending.rst:1096 msgid "" "Since it is written in Python, the :meth:`!__del__` method can execute " "arbitrary Python code. Could it perhaps do something to invalidate the " @@ -1049,37 +1660,66 @@ msgid "" "associated with it, thereby invalidating ``item``." msgstr "" -#: ../../extending/extending.rst:1055 +#: ../../extending/extending.rst:1104 msgid "" "The solution, once you know the source of the problem, is easy: temporarily " "increment the reference count. The correct version of the function reads::" msgstr "" +"A solução, depois de descobrir a origem do problema, é fácil: incrementar " +"temporariamente a contagem de referências. A versão correta da função é:" -#: ../../extending/extending.rst:1069 +#: ../../extending/extending.rst:1107 +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:1118 msgid "" "This is a true story. An older version of Python contained variants of this " "bug and someone spent a considerable amount of time in a C debugger to " "figure out why his :meth:`!__del__` methods would fail..." msgstr "" -#: ../../extending/extending.rst:1073 +#: ../../extending/extending.rst:1122 msgid "" "The second case of problems with a borrowed reference is a variant involving " "threads. Normally, multiple threads in the Python interpreter can't get in " -"each other's way, because there is a global lock protecting Python's entire " -"object space. However, it is possible to temporarily release this lock " -"using the macro :c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it " -"using :c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O " -"calls, to let other threads use the processor while waiting for the I/O to " -"complete. Obviously, the following function has the same problem as the " -"previous one::" +"each other's way, because there is a :term:`global lock ` protecting Python's entire object space. However, it is possible to " +"temporarily release this lock using the macro :c:macro:" +"`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using :c:macro:" +"`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to let " +"other threads use the processor while waiting for the I/O to complete. " +"Obviously, the following function has the same problem as the previous one::" msgstr "" -#: ../../extending/extending.rst:1096 -msgid "NULL Pointers" +#: ../../extending/extending.rst:1132 +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:1098 +#: ../../extending/extending.rst:1146 +msgid "NULL Pointers" +msgstr "Ponteiros NULL" + +#: ../../extending/extending.rst:1148 msgid "" "In general, functions that take object references as arguments do not expect " "you to pass them ``NULL`` pointers, and will dump core (or cause later core " @@ -1091,21 +1731,21 @@ msgid "" "more slowly." msgstr "" -#: ../../extending/extending.rst:1106 +#: ../../extending/extending.rst:1156 msgid "" "It is better to test for ``NULL`` only at the \"source:\" when a pointer " "that may be ``NULL`` is received, for example, from :c:func:`malloc` or from " "a function that may raise an exception." msgstr "" -#: ../../extending/extending.rst:1110 +#: ../../extending/extending.rst:1160 msgid "" "The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for " "``NULL`` pointers --- however, their variants :c:func:`Py_XINCREF` and :c:" "func:`Py_XDECREF` do." msgstr "" -#: ../../extending/extending.rst:1114 +#: ../../extending/extending.rst:1164 msgid "" "The macros for checking for a particular object type (``Pytype_Check()``) " "don't check for ``NULL`` pointers --- again, there is much code that calls " @@ -1114,24 +1754,24 @@ msgid "" "variants with ``NULL`` checking." msgstr "" -#: ../../extending/extending.rst:1120 +#: ../../extending/extending.rst:1170 msgid "" "The C function calling mechanism guarantees that the argument list passed to " "C functions (``args`` in the examples) is never ``NULL`` --- in fact it " "guarantees that it is always a tuple [#]_." msgstr "" -#: ../../extending/extending.rst:1124 +#: ../../extending/extending.rst:1174 msgid "" "It is a severe error to ever let a ``NULL`` pointer \"escape\" to the Python " "user." msgstr "" -#: ../../extending/extending.rst:1135 +#: ../../extending/extending.rst:1185 msgid "Writing Extensions in C++" -msgstr "" +msgstr "Escrevendo extensões em C++" -#: ../../extending/extending.rst:1137 +#: ../../extending/extending.rst:1187 msgid "" "It is possible to write extension modules in C++. Some restrictions apply. " "If the main program (the Python interpreter) is compiled and linked by the C " @@ -1143,12 +1783,22 @@ msgid "" "`` --- they use this form already if the symbol ``__cplusplus`` is defined " "(all recent C++ compilers define this symbol)." msgstr "" - -#: ../../extending/extending.rst:1151 +"É possível escrever módulos de extensão em C++. Algumas restrições se " +"aplicam. Se o programa principal (o interpretador Python) for compilado e " +"vinculado pelo compilador C, objetos globais ou estáticos com construtores " +"não poderão ser usados. Isso não é um problema se o programa principal for " +"vinculado pelo compilador C++. Funções que serão chamadas pelo interpretador " +"Python (em particular, funções de inicialização de módulos) devem ser " +"declaradas usando ``extern \"C\"``. Não é necessário incluir os arquivos de " +"cabeçalho Python entre ``extern \"C\" {...}`` --- eles já usam esta forma se " +"o símbolo ``__cplusplus`` estiver definido (todos os compiladores C++ " +"recentes definem este símbolo)." + +#: ../../extending/extending.rst:1201 msgid "Providing a C API for an Extension Module" -msgstr "" +msgstr "Fornecendo uma API C para um módulo de extensão" -#: ../../extending/extending.rst:1156 +#: ../../extending/extending.rst:1206 msgid "" "Many extension modules just provide new functions and types to be used from " "Python, but sometimes the code in an extension module can be useful for " @@ -1158,8 +1808,16 @@ msgid "" "create and manipulate lists, this new collection type should have a set of C " "functions for direct manipulation from other extension modules." msgstr "" +"Muitos módulos de extensão apenas fornecem novas funções e tipos para serem " +"usados em Python, mas às vezes o código em um módulo de extensão pode ser " +"útil para outros módulos de extensão. Por exemplo, um módulo de extensão " +"poderia implementar um tipo \"collection\", que funciona como listas sem " +"ordem. Assim como o tipo de lista padrão do Python possui uma API C que " +"permite que os módulos de extensão criem e manipulem listas, esse novo tipo " +"de coleção deve ter um conjunto de funções em C para manipulação direta de " +"outros módulos de extensão." -#: ../../extending/extending.rst:1164 +#: ../../extending/extending.rst:1214 msgid "" "At first sight this seems easy: just write the functions (without declaring " "them ``static``, of course), provide an appropriate header file, and " @@ -1174,8 +1832,21 @@ msgid "" "if symbols are globally visible, the module whose functions one wishes to " "call might not have been loaded yet!" msgstr "" - -#: ../../extending/extending.rst:1176 +"À primeira vista, isso parece fácil: basta escrever as funções (sem declará-" +"las ``static``, é claro), fornecer um arquivo de cabeçalho apropriado e " +"documentar a API C. E, de fato, isso funcionaria se todos os módulos de " +"extensão estivessem sempre vinculados estaticamente ao interpretador Python. " +"Quando os módulos são usados como bibliotecas compartilhadas, no entanto, os " +"símbolos definidos em um módulo podem não ser visíveis para outro módulo. Os " +"detalhes de visibilidade dependem do sistema operacional; alguns sistemas " +"usam um espaço de nomes global para o interpretador Python e todos os " +"módulos de extensão (Windows, por exemplo), enquanto outros exigem uma lista " +"explícita de símbolos importados no momento da vinculação do módulo (AIX é " +"um exemplo) ou oferecem uma escolha de estratégias diferentes (a maioria dos " +"Unices). E mesmo que os símbolos sejam globalmente visíveis, o módulo cujas " +"funções se deseja chamar pode não ter sido carregado ainda!" + +#: ../../extending/extending.rst:1226 msgid "" "Portability therefore requires not to make any assumptions about symbol " "visibility. This means that all symbols in extension modules should be " @@ -1184,8 +1855,15 @@ msgid "" "section :ref:`methodtable`). And it means that symbols that *should* be " "accessible from other extension modules must be exported in a different way." msgstr "" +"A portabilidade, portanto, exige que não se façam suposições sobre a " +"visibilidade dos símbolos. Isso significa que todos os símbolos em módulos " +"de extensão devem ser declarados ``static``, exceto a função de " +"inicialização do módulo, a fim de evitar conflitos de nomes com outros " +"módulos de extensão (conforme discutido na seção :ref:`methodtable`). E " +"significa que os símbolos que *deveriam* ser acessíveis a partir de outros " +"módulos de extensão devem ser exportados de uma maneira diferente." -#: ../../extending/extending.rst:1183 +#: ../../extending/extending.rst:1233 msgid "" "Python provides a special mechanism to pass C-level information (pointers) " "from one extension module to another one: Capsules. A Capsule is a Python " @@ -1197,7 +1875,7 @@ msgid "" "the Capsule." msgstr "" -#: ../../extending/extending.rst:1191 +#: ../../extending/extending.rst:1241 msgid "" "There are many ways in which Capsules can be used to export the C API of an " "extension module. Each function could get its own Capsule, or all C API " @@ -1206,8 +1884,14 @@ msgid "" "distributed in different ways between the module providing the code and the " "client modules." msgstr "" +"Existem muitas maneiras de usar Cápsulas para exportar a API C de um módulo " +"de extensão. Cada função pode obter sua própria Cápsula, ou todos os " +"ponteiros da API C podem ser armazenados em um array cujo endereço é " +"publicado em uma Cápsula. E as diversas tarefas de armazenamento e " +"recuperação dos ponteiros podem ser distribuídas de diferentes maneiras " +"entre o módulo que fornece o código e os módulos clientes." -#: ../../extending/extending.rst:1197 +#: ../../extending/extending.rst:1247 msgid "" "Whichever method you choose, it's important to name your Capsules properly. " "The function :c:func:`PyCapsule_New` takes a name parameter (:c:expr:`const " @@ -1217,13 +1901,19 @@ msgid "" "from another." msgstr "" -#: ../../extending/extending.rst:1204 +#: ../../extending/extending.rst:1254 msgid "" "In particular, Capsules used to expose C APIs should be given a name " "following this convention::" msgstr "" +"Em particular, as Cápsulas usadas para expor APIs C devem receber um nome " +"seguindo esta convenção:" + +#: ../../extending/extending.rst:1257 +msgid "modulename.attributename" +msgstr "" -#: ../../extending/extending.rst:1209 +#: ../../extending/extending.rst:1259 msgid "" "The convenience function :c:func:`PyCapsule_Import` makes it easy to load a " "C API provided via a Capsule, but only if the Capsule's name matches this " @@ -1231,7 +1921,7 @@ msgid "" "the Capsule they load contains the correct C API." msgstr "" -#: ../../extending/extending.rst:1214 +#: ../../extending/extending.rst:1264 msgid "" "The following example demonstrates an approach that puts most of the burden " "on the writer of the exporting module, which is appropriate for commonly " @@ -1242,7 +1932,7 @@ msgid "" "modules only have to call this macro before accessing the C API." msgstr "" -#: ../../extending/extending.rst:1222 +#: ../../extending/extending.rst:1272 msgid "" "The exporting module is a modification of the :mod:`!spam` module from " "section :ref:`extending-simpleexample`. The function :func:`!spam.system` " @@ -1253,59 +1943,183 @@ msgid "" "modules." msgstr "" -#: ../../extending/extending.rst:1229 +#: ../../extending/extending.rst:1279 msgid "" "The function :c:func:`!PySpam_System` is a plain C function, declared " "``static`` like everything else::" msgstr "" -#: ../../extending/extending.rst:1238 +#: ../../extending/extending.rst:1282 +msgid "" +"static int\n" +"PySpam_System(const char *command)\n" +"{\n" +" return system(command);\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:1288 msgid "The function :c:func:`!spam_system` is modified in a trivial way::" msgstr "" -#: ../../extending/extending.rst:1252 +#: ../../extending/extending.rst:1290 +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:1302 msgid "In the beginning of the module, right after the line ::" +msgstr "No início do módulo, logo após a linha ::" + +#: ../../extending/extending.rst:1304 +msgid "#include " msgstr "" -#: ../../extending/extending.rst:1256 +#: ../../extending/extending.rst:1306 msgid "two more lines must be added::" -msgstr "" +msgstr "mais duas linhas devem ser adicionadas::" -#: ../../extending/extending.rst:1261 +#: ../../extending/extending.rst:1308 msgid "" -"The ``#define`` is used to tell the header file that it is being included in " -"the exporting module, not a client module. Finally, the module's " -"initialization function must take care of initializing the C API pointer " -"array::" +"#define SPAM_MODULE\n" +"#include \"spammodule.h\"" msgstr "" -#: ../../extending/extending.rst:1290 +#: ../../extending/extending.rst:1311 +msgid "" +"The ``#define`` is used to tell the header file that it is being included in " +"the exporting module, not a client module. Finally, the module's :c:data:" +"`mod_exec ` function must take care of initializing the C API " +"pointer array::" +msgstr "" + +#: ../../extending/extending.rst:1315 +msgid "" +"static int\n" +"spam_module_exec(PyObject *m)\n" +"{\n" +" static void *PySpam_API[PySpam_API_pointers];\n" +" PyObject *c_api_object;\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" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}" +msgstr "" + +#: ../../extending/extending.rst:1334 msgid "" "Note that ``PySpam_API`` is declared ``static``; otherwise the pointer array " "would disappear when :c:func:`!PyInit_spam` terminates!" msgstr "" -#: ../../extending/extending.rst:1293 +#: ../../extending/extending.rst:1337 msgid "" "The bulk of the work is in the header file :file:`spammodule.h`, which looks " "like this::" msgstr "" - -#: ../../extending/extending.rst:1344 +"A maior parte do trabalho está no arquivo de cabeçalho :file:`spammodule.h`, " +"que se parece com isso::" + +#: ../../extending/extending.rst:1340 +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:1388 msgid "" "All that a client module must do in order to have access to the function :c:" "func:`!PySpam_System` is to call the function (or rather macro) :c:func:`!" -"import_spam` in its initialization function::" +"import_spam` in its :c:data:`mod_exec ` function::" +msgstr "" + +#: ../../extending/extending.rst:1392 +msgid "" +"static int\n" +"client_module_exec(PyObject *m)\n" +"{\n" +" if (import_spam() < 0) {\n" +" return -1;\n" +" }\n" +" /* additional initialization can happen here */\n" +" return 0;\n" +"}" msgstr "" -#: ../../extending/extending.rst:1362 +#: ../../extending/extending.rst:1402 msgid "" "The main disadvantage of this approach is that the file :file:`spammodule.h` " "is rather complicated. However, the basic structure is the same for each " "function that is exported, so it has to be learned only once." msgstr "" -#: ../../extending/extending.rst:1366 +#: ../../extending/extending.rst:1406 msgid "" "Finally it should be mentioned that Capsules offer additional functionality, " "which is especially useful for memory allocation and deallocation of the " @@ -1314,48 +2128,58 @@ msgid "" "Capsules (files :file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` " "in the Python source code distribution)." msgstr "" +"Por fim, vale mencionar que as Cápsulas oferecem funcionalidades adicionais, " +"especialmente úteis para alocação e desalocação de memória do ponteiro " +"armazenado em uma Cápsula. Os detalhes são descritos no Manual de Referência " +"da API Python/C, na seção :ref:`capsules` e na implementação das Cápsulas " +"(arquivos :file:`Include/pycapsule.h` e :file:`Objects/pycapsule.c` na " +"distribuição do código-fonte Python)." -#: ../../extending/extending.rst:1374 +#: ../../extending/extending.rst:1414 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../extending/extending.rst:1375 +#: ../../extending/extending.rst:1415 msgid "" "An interface for this function already exists in the standard module :mod:" "`os` --- it was chosen as a simple and straightforward example." msgstr "" +"Uma interface para esta função já existe no módulo padrão :mod:`os` --- ela " +"foi escolhida como um exemplo simples e direto." -#: ../../extending/extending.rst:1378 +#: ../../extending/extending.rst:1418 msgid "" "The metaphor of \"borrowing\" a reference is not completely correct: the " "owner still has a copy of the reference." msgstr "" +"A metáfora de \"pegar emprestado\" uma referência não é completamente " +"correta: o proprietário ainda tem uma cópia da referência." -#: ../../extending/extending.rst:1381 +#: ../../extending/extending.rst:1421 msgid "" "Checking that the reference count is at least 1 **does not work** --- the " "reference count itself could be in freed memory and may thus be reused for " "another object!" msgstr "" -#: ../../extending/extending.rst:1385 +#: ../../extending/extending.rst:1425 msgid "" "These guarantees don't hold when you use the \"old\" style calling " "convention --- this is still found in much existing code." msgstr "" -#: ../../extending/extending.rst:550 +#: ../../extending/extending.rst:593 msgid "PyObject_CallObject (C function)" msgstr "" -#: ../../extending/extending.rst:641 +#: ../../extending/extending.rst:684 msgid "PyArg_ParseTuple (C function)" msgstr "" -#: ../../extending/extending.rst:733 +#: ../../extending/extending.rst:776 msgid "PyArg_ParseTupleAndKeywords (C function)" msgstr "" -#: ../../extending/extending.rst:754 +#: ../../extending/extending.rst:797 msgid "Philbrick, Geoff" msgstr "" diff --git a/extending/index.po b/extending/index.po index 3d1f6e498..43d6d7882 100644 --- a/extending/index.po +++ b/extending/index.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 , 2023 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../extending/index.rst:5 msgid "Extending and Embedding the Python Interpreter" -msgstr "Estendendo e Incorporando o Interpretador Python" +msgstr "Estendendo e incorporando o interpretador Python" #: ../../extending/index.rst:7 msgid "" @@ -42,10 +43,10 @@ msgstr "" "módulos podem não somente definir novas funções, mas também novos tipos de " "objetos e seu conjunto de métodos. O documento também descreve como " "incorporar o interpretador Python em outro aplicativo, de forma a utilizá-lo " -"como sendo um idiota estendido. Por fim, estudaremos como podemos compilar e " -"fazer a vinculação dos módulos de extensão para que estes possam ser " -"carregados dinamicamente (em tempo de execução) pelo interpretador, caso o " -"sistema operacional subjacente suportar esse recurso." +"como sendo uma extensão da linguagem. Por fim, estudaremos como podemos " +"compilar e fazer a vinculação dos módulos de extensão para que estes possam " +"ser carregados dinamicamente (em tempo de execução) pelo interpretador, caso " +"o sistema operacional subjacente suportar esse recurso." #: ../../extending/index.rst:15 msgid "" @@ -77,42 +78,20 @@ msgstr "Ferramentas de terceiros recomendadas" #: ../../extending/index.rst:28 msgid "" "This guide only covers the basic tools for creating extensions provided as " -"part of this version of CPython. Third party tools like `Cython `_, `cffi `_, `SWIG `_ and `Numba `_ offer both simpler and " -"more sophisticated approaches to creating C and C++ extensions for Python." -msgstr "" -"Esse guia cobre apenas as ferramentas básicas para a criação de extensões " -"fornecidas como parte desta versão do CPython. Ferramentas de terceiros como " -"`Cython `_, `cffi `_, " -"`SWIG `_ e `Numba `_ " -"oferecem abordagens mais simples e sofisticadas para criar extensões C e C++ " -"para Python." - -#: ../../extending/index.rst:37 -msgid "" -"`Python Packaging User Guide: Binary Extensions `_" +"part of this version of CPython. Some :ref:`third party tools ` " +"offer both simpler and more sophisticated approaches to creating C and C++ " +"extensions for Python." msgstr "" -"`Guia do Usuário de Empacotamento do Python: Extensões Binárias `_" +"Este guia aborda apenas as ferramentas básicas para a criação de extensões " +"fornecidas como parte desta versão do CPython. Algumas :ref:`ferramentas de " +"terceiros ` oferecem abordagens mais simples e mais " +"sofisticadas para a criação de extensões em C e C++ para Python." -#: ../../extending/index.rst:38 -msgid "" -"The Python Packaging User Guide not only covers several available tools that " -"simplify the creation of binary extensions, but also discusses the various " -"reasons why creating an extension module may be desirable in the first place." -msgstr "" -"O Guia do Usuário de Empacotamento do Python não abrange apenas várias " -"ferramentas disponíveis que simplificam a criação de extensões binárias, mas " -"também discute os vários motivos pelos quais a criação de um módulo de " -"extensão pode ser desejável em primeiro lugar." - -#: ../../extending/index.rst:45 +#: ../../extending/index.rst:35 msgid "Creating extensions without third party tools" msgstr "Criando extensões sem ferramentas de terceiros" -#: ../../extending/index.rst:47 +#: ../../extending/index.rst:37 msgid "" "This section of the guide covers creating C and C++ extensions without " "assistance from third party tools. It is intended primarily for creators of " @@ -124,11 +103,15 @@ msgstr "" "ferramentas, em vez de ser uma maneira recomendada de criar suas próprias " "extensões C." -#: ../../extending/index.rst:63 +#: ../../extending/index.rst:44 +msgid ":pep:`489` -- Multi-phase extension module initialization" +msgstr ":pep:`489` -- Inicialização de módulo extensão multifase" + +#: ../../extending/index.rst:57 msgid "Embedding the CPython runtime in a larger application" msgstr "Incorporando o tempo de execução do CPython em uma aplicação maior" -#: ../../extending/index.rst:65 +#: ../../extending/index.rst:59 msgid "" "Sometimes, rather than creating an extension that runs inside the Python " "interpreter as the main application, it is desirable to instead embed the " diff --git a/extending/newtypes.po b/extending/newtypes.po index 19ec24aca..1af00f415 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..6c9f98d5c 100644 --- a/extending/newtypes_tutorial.po +++ b/extending/newtypes_tutorial.po @@ -1,27 +1,27 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# Rainer Terroso, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rainer Terroso, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,11 +37,12 @@ msgid "" "pattern, but there are some details that you need to understand before you " "can get started. This document is a gentle introduction to the topic." msgstr "" -"O Python permite que o gravador de um módulo de extensão C defina novos " -"tipos que podem ser manipulados a partir do código Python, da mesma forma " -"que os tipos embutidos :class:`str` e :class:`list`. O código para todos os " -"tipos de extensão segue um padrão, mas há alguns detalhes que você precisa " -"entender antes de começar. Este documento é uma introdução suave ao tópico." +"O Python permite que o desenvolvedor de um módulo de extensão em C defina " +"novos tipos que podem ser manipulados a partir do código Python, da mesma " +"forma que os tipos embutidos :class:`str` e :class:`list`. O código para de " +"todos tipos de extensão segue um padrão, mas há alguns detalhes que você " +"precisa entender antes de começar. Este documento é uma introdução suave ao " +"tópico." #: ../../extending/newtypes_tutorial.rst:24 msgid "The Basics" @@ -58,6 +59,14 @@ msgid "" "an object, a method called, or it is multiplied by another object. These C " "functions are called \"type methods\"." msgstr "" +"O tempo de execução do :term:`CPython` trata todos os objetos Python como " +"variáveis do tipo :c:expr:`PyObject*`, que funciona como um “tipo base” para " +"todos os objetos Python. A estrutura :c:type:`PyObject` em si contém apenas " +"a :term:`contagem de referências` do objeto e um ponteiro para o “objeto de " +"tipo” correspondente. É nesse objeto de tipo que tudo acontece: ele " +"determina quais funções em C o interpretador chama quando, por exemplo, um " +"atributo é acessado em um objeto, um método é chamado ou o objeto é " +"multiplicado por outro. Essas funções em C são chamadas de “métodos de tipo”." #: ../../extending/newtypes_tutorial.rst:35 msgid "" @@ -73,6 +82,9 @@ msgid "" "but complete, module that defines a new type named :class:`!Custom` inside a " "C extension module :mod:`!custom`:" msgstr "" +"Esse tipo de coisa só pode ser explicado por exemplo, então aqui está um " +"módulo mínimo, mas completo, que define um novo tipo chamado :class:`!" +"Custom` dentro de um módulo de extensão C :mod:`!custom`:" #: ../../extending/newtypes_tutorial.rst:43 msgid "" @@ -81,21 +93,139 @@ msgid "" "allows defining heap-allocated extension types using the :c:func:" "`PyType_FromSpec` function, which isn't covered in this tutorial." msgstr "" +"O que estamos mostrando aqui é a maneira tradicional de definir tipos de " +"extensão *estáticos*. Deve ser adequada para a maioria dos usos. A API C " +"também permite definir tipos de extensão alocados em heap usando a função :c:" +"func:`PyType_FromSpec`, que não é abordada neste tutorial." + +#: ../../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 int\n" +"custom_module_exec(PyObject *m)\n" +"{\n" +" if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot custom_module_slots[] = {\n" +" {Py_mod_exec, custom_module_exec},\n" +" // Just use this while using static types\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef custom_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = custom_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom(void)\n" +"{\n" +" return PyModuleDef_Init(&custom_module);\n" +"}\n" +msgstr "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" /* Campos específico do tipo vão aqui. */\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 int\n" +"custom_module_exec(PyObject *m)\n" +"{\n" +" if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot custom_module_slots[] = {\n" +" {Py_mod_exec, custom_module_exec},\n" +" // Só use isso quando estiver usando tipos estáticos\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef custom_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = custom_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom(void)\n" +"{\n" +" return PyModuleDef_Init(&custom_module);\n" +"}\n" #: ../../extending/newtypes_tutorial.rst:50 msgid "" "Now that's quite a bit to take in at once, but hopefully bits will seem " "familiar from the previous chapter. This file defines three things:" msgstr "" -"Agora isso é um pouco para ser absorvido de uma só vez, mas esperamos que os " -"bits pareçam familiares no capítulo anterior. Este arquivo define três " -"coisas:" +"Isso é bastante informação para assimilar de uma só vez, mas algumas partes " +"devem parecer familiares pelo que foi visto no capítulo anterior. Este " +"arquivo define três elementos:" #: ../../extending/newtypes_tutorial.rst:53 msgid "" "What a :class:`!Custom` **object** contains: this is the ``CustomObject`` " "struct, which is allocated once for each :class:`!Custom` instance." msgstr "" +"O que um **objeto** :class:`!Custom` contém: esta é uma estrutura " +"``CustomObject``, alocada uma vez para cada instância de :class:`!Custom`." #: ../../extending/newtypes_tutorial.rst:55 msgid "" @@ -103,18 +233,38 @@ msgid "" "struct, which defines a set of flags and function pointers that the " "interpreter inspects when specific operations are requested." msgstr "" +"Como o **tipo** :class:`!Custom` se comporta: esta é a estrutura " +"``CustomType``, que define um conjunto de sinalizadores e ponteiros de " +"função que o interpretador inspeciona quando operações específicas são " +"solicitadas." #: ../../extending/newtypes_tutorial.rst:58 msgid "" -"How to initialize the :mod:`!custom` module: this is the ``PyInit_custom`` " -"function and the associated ``custommodule`` struct." +"How to define and execute the :mod:`!custom` module: this is the " +"``PyInit_custom`` function and the associated ``custom_module`` struct for " +"defining the module, and the ``custom_module_exec`` function to set up a " +"fresh module object." msgstr "" +"Como definir e executar o módulo :mod:`!custom`: esta é a função " +"``PyInit_custom`` e a estrutura associada ``custom_module`` para definir o " +"módulo, e a função ``custom_module_exec`` para configurar um novo objeto de " +"módulo." -#: ../../extending/newtypes_tutorial.rst:61 +#: ../../extending/newtypes_tutorial.rst:63 msgid "The first bit is::" msgstr "O primeiro bit é ::" -#: ../../extending/newtypes_tutorial.rst:67 +#: ../../extending/newtypes_tutorial.rst:65 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} CustomObject;" +msgstr "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} CustomObject;" + +#: ../../extending/newtypes_tutorial.rst:69 msgid "" "This is what a Custom object will contain. ``PyObject_HEAD`` is mandatory " "at the start of each object struct and defines a field called ``ob_base`` of " @@ -124,56 +274,135 @@ msgid "" "abstract away the layout and to enable additional fields in :ref:`debug " "builds `." msgstr "" +"Isto é o que um objeto Custom conterá. ``PyObject_HEAD`` é obrigatório no " +"início de cada estrutura de objeto e define um campo chamado ``ob_base`` do " +"tipo :c:type:`PyObject`, contendo um ponteiro para um objeto de tipo e uma " +"contagem de referências (esses podem ser acessados usando os macros :c:macro:" +"`Py_TYPE` e :c:macro:`Py_REFCNT`, respectivamente). O objetivo do macro é " +"abstrair o layout e permitir campos adicionais em :ref:`construções de " +"depuração `." -#: ../../extending/newtypes_tutorial.rst:76 +#: ../../extending/newtypes_tutorial.rst:78 msgid "" "There is no semicolon above after the :c:macro:`PyObject_HEAD` macro. Be " "wary of adding one by accident: some compilers will complain." msgstr "" +"Não há ponto e vírgula acima após o macro :c:macro:`PyObject_HEAD`. Tenha " +"cuidado para não adicionar um por engano: alguns compiladores podem emitir " +"erros." -#: ../../extending/newtypes_tutorial.rst:79 +#: ../../extending/newtypes_tutorial.rst:81 msgid "" "Of course, objects generally store additional data besides the standard " "``PyObject_HEAD`` boilerplate; for example, here is the definition for " "standard Python floats::" msgstr "" +"Obviamente, objetos geralmente armazenam dados adicionais além do padrão " +"``PyObject_HEAD`` boilerplate; por exemplo, aqui está a definição do padrão " +"Python floats::" -#: ../../extending/newtypes_tutorial.rst:88 +#: ../../extending/newtypes_tutorial.rst:85 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" double ob_fval;\n" +"} PyFloatObject;" +msgstr "" +"typedef struct {\n" +" PyObject_HEAD\n" +" double ob_fval;\n" +"} PyFloatObject;" + +#: ../../extending/newtypes_tutorial.rst:90 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:101 +#: ../../extending/newtypes_tutorial.rst:92 +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 "" +"estático PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objeto\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT,\n" +" .tp_new = PyType_GenericNew,\n" +"};" + +#: ../../extending/newtypes_tutorial.rst:103 msgid "" "We recommend using C99-style designated initializers as above, to avoid " "listing all the :c:type:`PyTypeObject` fields that you don't care about and " "also to avoid caring about the fields' declaration order." msgstr "" +"Recomendamos usar inicializadores nomeados no estilo C99, como mostrado " +"acima, para evitar listar todos os campos de :c:type:`PyTypeObject` com os " +"quais você não precisa se preocupar e também para não depender da ordem de " +"declaração desses campos" -#: ../../extending/newtypes_tutorial.rst:105 +#: ../../extending/newtypes_tutorial.rst:107 msgid "" "The actual definition of :c:type:`PyTypeObject` in :file:`object.h` has many " "more :ref:`fields ` than the definition above. The remaining " "fields will be filled with zeros by the C compiler, and it's common practice " "to not specify them explicitly unless you need them." msgstr "" +"A definição real de :c:type:`PyTypeObject` no :file:`object.h` possui muito " +"mais ref:`fields do que a definição acima. Os campos " +"restantes serão preenchidos com zeros pelo compilador C, e é prática comum " +"não especificá-los explicitamente, a menos que sejam necessários." -#: ../../extending/newtypes_tutorial.rst:110 +#: ../../extending/newtypes_tutorial.rst:112 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:114 +msgid ".ob_base = PyVarObject_HEAD_INIT(NULL, 0)" +msgstr ".ob_base = PyVarObject_HEAD_INIT(NULL, 0)" + +#: ../../extending/newtypes_tutorial.rst:116 msgid "" "This line is mandatory boilerplate to initialize the ``ob_base`` field " "mentioned above. ::" msgstr "" +"Essa linha é um boilerplate obrigatório para inicializar o campo ``ob_base`` " +"mencionado acima. ::" #: ../../extending/newtypes_tutorial.rst:119 +msgid ".tp_name = \"custom.Custom\"," +msgstr ".tp_name = \"custom.Custom\"," + +#: ../../extending/newtypes_tutorial.rst:121 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 "" +"O nome do nosso tipo. Ele aparecerá na representação textual padrão do " +"nosso objeto e em algumas mensagens erro, por exemplo:" -#: ../../extending/newtypes_tutorial.rst:129 +#: ../../extending/newtypes_tutorial.rst:124 +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 "" +">>> \"\" + custom.Custom()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: can only concatenate str (not \"custom.Custom\") to str" + +#: ../../extending/newtypes_tutorial.rst:131 msgid "" "Note that the name is a dotted name that includes both the module name and " "the name of the type within the module. The module in this case is :mod:`!" @@ -181,21 +410,38 @@ msgid "" "`!custom.Custom`. Using the real dotted import path is important to make " "your type compatible with the :mod:`pydoc` and :mod:`pickle` modules. ::" msgstr "" +"Observe que o nome é um nome pontilhado que inclui o nome módulo e o nome do " +"tipo dentro do módulo. O módulo, neste caso, é :mod:`!custom` e o tipo é :" +"class:`!Custom`, portanto, definimos o nome do tipo como :class:`!custom." +"Custom`. O uso do pontilhado real caminho de importação é importante para " +"tornar seu tipo compatível com o :mod:`pydoc` e os módulos :mod:`pickle`. ::" -#: ../../extending/newtypes_tutorial.rst:138 +#: ../../extending/newtypes_tutorial.rst:137 +msgid "" +".tp_basicsize = sizeof(CustomObject),\n" +".tp_itemsize = 0," +msgstr "" +".tp_basicsize = sizeof(CustomObject),\n" +".tp_itemsize = 0," + +#: ../../extending/newtypes_tutorial.rst:140 msgid "" "This is so that Python knows how much memory to allocate when creating new :" "class:`!Custom` instances. :c:member:`~PyTypeObject.tp_itemsize` is only " "used for variable-sized objects and should otherwise be zero." msgstr "" +"Isso serve para que o Python saiba quanta memória deve ser alocada ao criar " +"novas instâncias do :class:`!Custom`. O :c:member:`~PyTypeObject." +"tp_itemsize` é usado somente para objeto de tamanho variável e, caso " +"contrário, deve ser zero." -#: ../../extending/newtypes_tutorial.rst:144 +#: ../../extending/newtypes_tutorial.rst:146 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 " @@ -203,23 +449,31 @@ msgid "" "your base type, and therefore increasing its size." msgstr "" -#: ../../extending/newtypes_tutorial.rst:154 +#: ../../extending/newtypes_tutorial.rst:156 msgid "We set the class flags to :c:macro:`Py_TPFLAGS_DEFAULT`. ::" msgstr "" #: ../../extending/newtypes_tutorial.rst:158 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:160 msgid "" "All types should include this constant in their flags. It enables all of " "the members defined until at least Python 3.3. If you need further members, " "you will need to OR the corresponding flags." msgstr "" -#: ../../extending/newtypes_tutorial.rst:162 +#: ../../extending/newtypes_tutorial.rst:164 msgid "" "We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. ::" msgstr "" #: ../../extending/newtypes_tutorial.rst:166 +msgid ".tp_doc = PyDoc_STR(\"Custom objects\")," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:168 msgid "" "To enable object creation, we have to provide a :c:member:`~PyTypeObject." "tp_new` handler. This is the equivalent of the Python method :meth:`~object." @@ -229,50 +483,96 @@ msgid "" msgstr "" #: ../../extending/newtypes_tutorial.rst:173 +msgid ".tp_new = PyType_GenericNew," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:175 msgid "" "Everything else in the file should be familiar, except for some code in :c:" -"func:`!PyInit_custom`::" +"func:`!custom_module_exec`::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:179 +#: ../../extending/newtypes_tutorial.rst:178 +msgid "" +"if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +"}" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:182 msgid "" "This initializes the :class:`!Custom` type, filling in a number of members " "to the appropriate default values, including :c:member:`~PyObject.ob_type` " "that we initially set to ``NULL``. ::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:188 +#: ../../extending/newtypes_tutorial.rst:186 +msgid "" +"if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) {\n" +" return -1;\n" +"}" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:190 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:196 +#: ../../extending/newtypes_tutorial.rst:193 +msgid "" +">>> import custom\n" +">>> mycustom = custom.Custom()" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:198 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:201 +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:203 msgid "in a file called :file:`pyproject.toml`, and" msgstr "" -#: ../../extending/newtypes_tutorial.rst:208 +#: ../../extending/newtypes_tutorial.rst:205 +msgid "" +"from setuptools import Extension, setup\n" +"setup(ext_modules=[Extension(\"custom\", [\"custom.c\"])])" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:210 msgid "in a file called :file:`setup.py`; then typing" msgstr "" -#: ../../extending/newtypes_tutorial.rst:214 +#: ../../extending/newtypes_tutorial.rst:212 +#: ../../extending/newtypes_tutorial.rst:527 +msgid "$ python -m pip install ." +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:216 msgid "" "in a shell should produce a file :file:`custom.so` in a subdirectory and " "install it; now fire up Python --- you should be able to ``import custom`` " "and play around with ``Custom`` objects." msgstr "" -#: ../../extending/newtypes_tutorial.rst:218 +#: ../../extending/newtypes_tutorial.rst:220 msgid "That wasn't so hard, was it?" msgstr "Isso não foi tão difícil, foi?" -#: ../../extending/newtypes_tutorial.rst:220 +#: ../../extending/newtypes_tutorial.rst:222 msgid "" "Of course, the current Custom type is pretty uninteresting. It has no data " "and doesn't do anything. It can't even be subclassed." @@ -280,22 +580,166 @@ msgstr "" "Naturalmente, o tipo personalizado atual é bastante desinteressante. Não tem " "dados e não faz nada. Não pode nem ser subclassificado." -#: ../../extending/newtypes_tutorial.rst:225 +#: ../../extending/newtypes_tutorial.rst:227 msgid "Adding data and methods to the Basic example" msgstr "Adicionando dados e métodos ao exemplo básico" -#: ../../extending/newtypes_tutorial.rst:227 +#: ../../extending/newtypes_tutorial.rst:229 msgid "" "Let's extend the basic example to add some data and methods. Let's also " "make the type usable as a base class. We'll create a new module, :mod:`!" "custom2` that adds these capabilities:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:234 +#: ../../extending/newtypes_tutorial.rst:233 +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 int\n" +"custom_module_exec(PyObject *m)\n" +"{\n" +" if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot custom_module_slots[] = {\n" +" {Py_mod_exec, custom_module_exec},\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef custom_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom2\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = custom_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom2(void)\n" +"{\n" +" return PyModuleDef_Init(&custom_module);\n" +"}\n" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:236 msgid "This version of the module has a number of changes." msgstr "Esta versão do módulo possui várias alterações." -#: ../../extending/newtypes_tutorial.rst:236 +#: ../../extending/newtypes_tutorial.rst:238 msgid "" "The :class:`!Custom` type now has three data attributes in its C struct, " "*first*, *last*, and *number*. The *first* and *last* variables are Python " @@ -303,21 +747,46 @@ msgid "" "integer." msgstr "" -#: ../../extending/newtypes_tutorial.rst:240 +#: ../../extending/newtypes_tutorial.rst:242 msgid "The object structure is updated accordingly::" msgstr "A estrutura do objeto é atualizada de acordo ::" -#: ../../extending/newtypes_tutorial.rst:249 +#: ../../extending/newtypes_tutorial.rst:244 +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:251 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:260 +#: ../../extending/newtypes_tutorial.rst:254 +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:262 msgid "which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member::" msgstr "" #: ../../extending/newtypes_tutorial.rst:264 +msgid ".tp_dealloc = (destructor) Custom_dealloc," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:266 msgid "" "This method first clears the reference counts of the two Python attributes. :" "c:func:`Py_XDECREF` correctly handles the case where its argument is " @@ -328,7 +797,7 @@ msgid "" "an instance of a subclass." msgstr "" -#: ../../extending/newtypes_tutorial.rst:273 +#: ../../extending/newtypes_tutorial.rst:275 msgid "" "The explicit cast to ``destructor`` above is needed because we defined " "``Custom_dealloc`` to take a ``CustomObject *`` argument, but the " @@ -337,17 +806,45 @@ msgid "" "oriented polymorphism, in C!" msgstr "" -#: ../../extending/newtypes_tutorial.rst:279 +#: ../../extending/newtypes_tutorial.rst:281 msgid "" "We want to make sure that the first and last names are initialized to empty " "strings, so we provide a ``tp_new`` implementation::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:303 +#: ../../extending/newtypes_tutorial.rst:284 +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:305 msgid "and install it in the :c:member:`~PyTypeObject.tp_new` member::" msgstr "" #: ../../extending/newtypes_tutorial.rst:307 +msgid ".tp_new = Custom_new," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:309 msgid "" "The ``tp_new`` handler is responsible for creating (as opposed to " "initializing) objects of the type. It is exposed in Python as the :meth:" @@ -358,7 +855,7 @@ msgid "" "``first`` and ``last`` attributes to non-``NULL`` default values." msgstr "" -#: ../../extending/newtypes_tutorial.rst:315 +#: ../../extending/newtypes_tutorial.rst:317 msgid "" "``tp_new`` is passed the type being instantiated (not necessarily " "``CustomType``, if a subclass is instantiated) and any arguments passed when " @@ -368,25 +865,29 @@ msgid "" "k.a. ``tp_init`` in C or ``__init__`` in Python) methods." msgstr "" -#: ../../extending/newtypes_tutorial.rst:323 +#: ../../extending/newtypes_tutorial.rst:325 msgid "" "``tp_new`` shouldn't call ``tp_init`` explicitly, as the interpreter will do " "it itself." msgstr "" -#: ../../extending/newtypes_tutorial.rst:326 +#: ../../extending/newtypes_tutorial.rst:328 msgid "" "The ``tp_new`` implementation calls the :c:member:`~PyTypeObject.tp_alloc` " "slot to allocate memory::" msgstr "" #: ../../extending/newtypes_tutorial.rst:331 +msgid "self = (CustomObject *) type->tp_alloc(type, 0);" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:333 msgid "" "Since memory allocation may fail, we must check the :c:member:`~PyTypeObject." "tp_alloc` result against ``NULL`` before proceeding." msgstr "" -#: ../../extending/newtypes_tutorial.rst:335 +#: ../../extending/newtypes_tutorial.rst:337 msgid "" "We didn't fill the :c:member:`~PyTypeObject.tp_alloc` slot ourselves. " "Rather :c:func:`PyType_Ready` fills it for us by inheriting it from our base " @@ -394,7 +895,7 @@ msgid "" "allocation strategy." msgstr "" -#: ../../extending/newtypes_tutorial.rst:341 +#: ../../extending/newtypes_tutorial.rst:343 msgid "" "If you are creating a co-operative :c:member:`~PyTypeObject.tp_new` (one " "that calls a base type's :c:member:`~PyTypeObject.tp_new` or :meth:`~object." @@ -407,17 +908,50 @@ msgid "" "subclasses without getting a :exc:`TypeError`.)" msgstr "" -#: ../../extending/newtypes_tutorial.rst:351 +#: ../../extending/newtypes_tutorial.rst:353 msgid "" "We also define an initialization function which accepts arguments to provide " "initial values for our instance::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:380 +#: ../../extending/newtypes_tutorial.rst:356 +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:382 msgid "by filling the :c:member:`~PyTypeObject.tp_init` slot. ::" msgstr "" #: ../../extending/newtypes_tutorial.rst:384 +msgid ".tp_init = (initproc) Custom_init," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:386 msgid "" "The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the :meth:" "`~object.__init__` method. It is used to initialize an object after it's " @@ -425,7 +959,7 @@ msgid "" "they should return either ``0`` on success or ``-1`` on error." msgstr "" -#: ../../extending/newtypes_tutorial.rst:389 +#: ../../extending/newtypes_tutorial.rst:391 msgid "" "Unlike the ``tp_new`` handler, there is no guarantee that ``tp_init`` is " "called at all (for example, the :mod:`pickle` module by default doesn't " @@ -436,7 +970,16 @@ msgid "" "``first`` member like this::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:403 +#: ../../extending/newtypes_tutorial.rst:399 +msgid "" +"if (first) {\n" +" Py_XDECREF(self->first);\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +"}" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:405 msgid "" "But this would be risky. Our type doesn't restrict the type of the " "``first`` member, so it could be any kind of object. It could have a " @@ -446,7 +989,7 @@ msgid "" "accesses and modifies our object." msgstr "" -#: ../../extending/newtypes_tutorial.rst:410 +#: ../../extending/newtypes_tutorial.rst:412 msgid "" "To be paranoid and protect ourselves against this possibility, we almost " "always reassign members before decrementing their reference counts. When " @@ -456,43 +999,60 @@ msgstr "" "sempre realocamos os membros antes de decrementar suas contagens de " "referência. Quando não temos que fazer isso?" -#: ../../extending/newtypes_tutorial.rst:414 +#: ../../extending/newtypes_tutorial.rst:416 msgid "when we absolutely know that the reference count is greater than 1;" msgstr "" "quando sabemos absolutamente que a contagem de referência é maior que 1;" -#: ../../extending/newtypes_tutorial.rst:416 +#: ../../extending/newtypes_tutorial.rst:418 msgid "" "when we know that deallocation of the object [#]_ will neither release the :" "term:`GIL` nor cause any calls back into our type's code;" msgstr "" -#: ../../extending/newtypes_tutorial.rst:419 +#: ../../extending/newtypes_tutorial.rst:421 msgid "" "when decrementing a reference count in a :c:member:`~PyTypeObject." "tp_dealloc` handler on a type which doesn't support cyclic garbage " "collection [#]_." msgstr "" -#: ../../extending/newtypes_tutorial.rst:422 +#: ../../extending/newtypes_tutorial.rst:424 msgid "" "We want to expose our instance variables as attributes. There are a number " "of ways to do that. The simplest way is to define member definitions::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:435 +#: ../../extending/newtypes_tutorial.rst:427 +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:437 msgid "" "and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot::" msgstr "" #: ../../extending/newtypes_tutorial.rst:439 +msgid ".tp_members = Custom_members," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:441 msgid "" "Each member definition has a member name, type, offset, access flags and " "documentation string. See the :ref:`Generic-Attribute-Management` section " "below for details." msgstr "" -#: ../../extending/newtypes_tutorial.rst:443 +#: ../../extending/newtypes_tutorial.rst:445 msgid "" "A disadvantage of this approach is that it doesn't provide a way to restrict " "the types of objects that can be assigned to the Python attributes. We " @@ -503,13 +1063,30 @@ msgid "" "deleted." msgstr "" -#: ../../extending/newtypes_tutorial.rst:450 +#: ../../extending/newtypes_tutorial.rst:452 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:467 +#: ../../extending/newtypes_tutorial.rst:455 +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:469 msgid "" "The method is implemented as a C function that takes a :class:`!Custom` (or :" "class:`!Custom` subclass) instance as the first argument. Methods always " @@ -519,7 +1096,13 @@ msgid "" "method is equivalent to the Python method:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:479 +#: ../../extending/newtypes_tutorial.rst:476 +msgid "" +"def name(self):\n" +" return \"%s %s\" % (self.first, self.last)" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:481 msgid "" "Note that we have to check for the possibility that our :attr:`!first` and :" "attr:`!last` members are ``NULL``. This is because they can be deleted, in " @@ -528,7 +1111,7 @@ msgid "" "We'll see how to do that in the next section." msgstr "" -#: ../../extending/newtypes_tutorial.rst:485 +#: ../../extending/newtypes_tutorial.rst:487 msgid "" "Now that we've defined the method, we need to create an array of method " "definitions::" @@ -536,17 +1119,31 @@ msgstr "" "Agora que definimos o método, precisamos criar uma array de definições de " "métodos::" -#: ../../extending/newtypes_tutorial.rst:495 +#: ../../extending/newtypes_tutorial.rst:490 +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:497 msgid "" "(note that we used the :c:macro:`METH_NOARGS` flag to indicate that the " "method is expecting no arguments other than *self*)" msgstr "" -#: ../../extending/newtypes_tutorial.rst:498 +#: ../../extending/newtypes_tutorial.rst:500 msgid "and assign it to the :c:member:`~PyTypeObject.tp_methods` slot::" msgstr "" #: ../../extending/newtypes_tutorial.rst:502 +msgid ".tp_methods = Custom_methods," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:504 msgid "" "Finally, we'll make our type usable as a base class for subclassing. We've " "written our methods carefully so far so that they don't make any assumptions " @@ -555,25 +1152,38 @@ msgid "" msgstr "" #: ../../extending/newtypes_tutorial.rst:509 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:511 msgid "" "We rename :c:func:`!PyInit_custom` to :c:func:`!PyInit_custom2`, update the " "module name in the :c:type:`PyModuleDef` struct, and update the full class " "name in the :c:type:`PyTypeObject` struct." msgstr "" -#: ../../extending/newtypes_tutorial.rst:513 +#: ../../extending/newtypes_tutorial.rst:515 msgid "Finally, we update our :file:`setup.py` file to include the new module," msgstr "" -#: ../../extending/newtypes_tutorial.rst:523 +#: ../../extending/newtypes_tutorial.rst:517 +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:525 msgid "and then we re-install so that we can ``import custom2``:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:530 +#: ../../extending/newtypes_tutorial.rst:532 msgid "Providing finer control over data attributes" msgstr "Fornecendo controle mais preciso sobre atributos de dados" -#: ../../extending/newtypes_tutorial.rst:532 +#: ../../extending/newtypes_tutorial.rst:534 msgid "" "In this section, we'll provide finer control over how the :attr:`!first` " "and :attr:`!last` attributes are set in the :class:`!Custom` example. In the " @@ -582,14 +1192,232 @@ msgid "" "make sure that these attributes always contain strings." msgstr "" -#: ../../extending/newtypes_tutorial.rst:541 +#: ../../extending/newtypes_tutorial.rst:540 +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 int\n" +"custom_module_exec(PyObject *m)\n" +"{\n" +" if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot custom_module_slots[] = {\n" +" {Py_mod_exec, custom_module_exec},\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef custom_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom3\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = custom_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom3(void)\n" +"{\n" +" return PyModuleDef_Init(&custom_module);\n" +"}\n" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:543 msgid "" "To provide greater control, over the :attr:`!first` and :attr:`!last` " "attributes, we'll use custom getter and setter functions. Here are the " "functions for getting and setting the :attr:`!first` attribute::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:572 +#: ../../extending/newtypes_tutorial.rst:547 +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:574 msgid "" "The getter function is passed a :class:`!Custom` object and a \"closure\", " "which is a void pointer. In this case, the closure is ignored. (The " @@ -599,7 +1427,7 @@ msgid "" "data in the closure.)" msgstr "" -#: ../../extending/newtypes_tutorial.rst:578 +#: ../../extending/newtypes_tutorial.rst:580 msgid "" "The setter function is passed the :class:`!Custom` object, the new value, " "and the closure. The new value may be ``NULL``, in which case the attribute " @@ -607,32 +1435,85 @@ msgid "" "deleted or if its new value is not a string." msgstr "" -#: ../../extending/newtypes_tutorial.rst:583 +#: ../../extending/newtypes_tutorial.rst:585 msgid "We create an array of :c:type:`PyGetSetDef` structures::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:593 +#: ../../extending/newtypes_tutorial.rst:587 +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:595 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:597 +msgid ".tp_getset = Custom_getsetters," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:599 msgid "" "The last item in a :c:type:`PyGetSetDef` structure is the \"closure\" " "mentioned above. In this case, we aren't using a closure, so we just pass " "``NULL``." msgstr "" -#: ../../extending/newtypes_tutorial.rst:600 +#: ../../extending/newtypes_tutorial.rst:602 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:608 +#: ../../extending/newtypes_tutorial.rst:604 +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:610 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:637 +#: ../../extending/newtypes_tutorial.rst:613 +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:639 msgid "" "With these changes, we can assure that the ``first`` and ``last`` members " "are never ``NULL`` so we can remove checks for ``NULL`` values in almost all " @@ -642,25 +1523,32 @@ msgid "" "possibility that the initialization of these members failed in ``tp_new``." msgstr "" -#: ../../extending/newtypes_tutorial.rst:644 +#: ../../extending/newtypes_tutorial.rst:646 msgid "" "We also rename the module initialization function and module name in the " "initialization function, as we did before, and we add an extra definition to " "the :file:`setup.py` file." msgstr "" -#: ../../extending/newtypes_tutorial.rst:650 +#: ../../extending/newtypes_tutorial.rst:652 msgid "Supporting cyclic garbage collection" msgstr "Apoiando a coleta de lixo cíclica" -#: ../../extending/newtypes_tutorial.rst:652 +#: ../../extending/newtypes_tutorial.rst:654 msgid "" "Python has a :term:`cyclic garbage collector (GC) ` that " "can identify unneeded objects even when their reference counts are not zero. " "This can happen when objects are involved in cycles. For example, consider:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:662 +#: ../../extending/newtypes_tutorial.rst:658 +msgid "" +">>> l = []\n" +">>> l.append(l)\n" +">>> del l" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:664 msgid "" "In this example, we create a list that contains itself. When we delete it, " "it still has a reference from itself. Its reference count doesn't drop to " @@ -668,7 +1556,7 @@ msgid "" "out that the list is garbage and free it." msgstr "" -#: ../../extending/newtypes_tutorial.rst:667 +#: ../../extending/newtypes_tutorial.rst:669 msgid "" "In the second version of the :class:`!Custom` example, we allowed any kind " "of object to be stored in the :attr:`!first` or :attr:`!last` attributes " @@ -677,7 +1565,16 @@ msgid "" "those two reasons, :class:`!Custom` objects can participate in cycles:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:681 +#: ../../extending/newtypes_tutorial.rst:675 +msgid "" +">>> import custom3\n" +">>> class Derived(custom3.Custom): pass\n" +"...\n" +">>> n = Derived()\n" +">>> n.some_attribute = n" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:683 msgid "" "To allow a :class:`!Custom` instance participating in a reference cycle to " "be properly detected and collected by the cyclic GC, our :class:`!Custom` " @@ -685,13 +1582,239 @@ msgid "" "these slots:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:688 +#: ../../extending/newtypes_tutorial.rst:687 +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 int\n" +"custom_module_exec(PyObject *m)\n" +"{\n" +" if (PyType_Ready(&CustomType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot custom_module_slots[] = {\n" +" {Py_mod_exec, custom_module_exec},\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef custom_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom4\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = custom_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom4(void)\n" +"{\n" +" return PyModuleDef_Init(&custom_module);\n" +"}\n" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:690 msgid "" "First, the traversal method lets the cyclic GC know about subobjects that " "could participate in cycles::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:708 +#: ../../extending/newtypes_tutorial.rst:693 +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:710 msgid "" "For each subobject that can participate in cycles, we need to call the :c:" "func:`!visit` function, which is passed to the traversal method. The :c:func:" @@ -700,26 +1823,48 @@ msgid "" "be returned if it is non-zero." msgstr "" -#: ../../extending/newtypes_tutorial.rst:714 +#: ../../extending/newtypes_tutorial.rst:716 msgid "" "Python provides a :c:func:`Py_VISIT` macro that automates calling visit " "functions. With :c:func:`Py_VISIT`, we can minimize the amount of " "boilerplate in ``Custom_traverse``::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:727 +#: ../../extending/newtypes_tutorial.rst:720 +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:729 msgid "" "The :c:member:`~PyTypeObject.tp_traverse` implementation must name its " "arguments exactly *visit* and *arg* in order to use :c:func:`Py_VISIT`." msgstr "" -#: ../../extending/newtypes_tutorial.rst:730 +#: ../../extending/newtypes_tutorial.rst:732 msgid "" "Second, we need to provide a method for clearing any subobjects that can " "participate in cycles::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:741 +#: ../../extending/newtypes_tutorial.rst:735 +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:743 msgid "" "Notice the use of the :c:func:`Py_CLEAR` macro. It is the recommended and " "safe way to clear data attributes of arbitrary types while decrementing " @@ -729,18 +1874,26 @@ msgid "" "again (*especially* if there is a reference cycle)." msgstr "" -#: ../../extending/newtypes_tutorial.rst:749 +#: ../../extending/newtypes_tutorial.rst:751 msgid "You could emulate :c:func:`Py_CLEAR` by writing::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:756 +#: ../../extending/newtypes_tutorial.rst:753 +msgid "" +"PyObject *tmp;\n" +"tmp = self->first;\n" +"self->first = NULL;\n" +"Py_XDECREF(tmp);" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:758 msgid "" "Nevertheless, it is much easier and less error-prone to always use :c:func:" "`Py_CLEAR` when deleting an attribute. Don't try to micro-optimize at the " "expense of robustness!" msgstr "" -#: ../../extending/newtypes_tutorial.rst:760 +#: ../../extending/newtypes_tutorial.rst:762 msgid "" "The deallocator ``Custom_dealloc`` may call arbitrary code when clearing " "attributes. It means the circular GC can be triggered inside the function. " @@ -750,24 +1903,40 @@ msgid "" "`PyObject_GC_UnTrack` and ``Custom_clear``::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:775 +#: ../../extending/newtypes_tutorial.rst:769 +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:777 msgid "" "Finally, we add the :c:macro:`Py_TPFLAGS_HAVE_GC` flag to the class flags::" msgstr "" #: ../../extending/newtypes_tutorial.rst:779 msgid "" +".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC," +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:781 +msgid "" "That's pretty much it. If we had written custom :c:member:`~PyTypeObject." "tp_alloc` or :c:member:`~PyTypeObject.tp_free` handlers, we'd need to modify " "them for cyclic garbage collection. Most extensions will use the versions " "automatically provided." msgstr "" -#: ../../extending/newtypes_tutorial.rst:785 +#: ../../extending/newtypes_tutorial.rst:787 msgid "Subclassing other types" msgstr "Criando subclasses de outros tipos" -#: ../../extending/newtypes_tutorial.rst:787 +#: ../../extending/newtypes_tutorial.rst:789 msgid "" "It is possible to create new extension types that are derived from existing " "types. It is easiest to inherit from the built in types, since an extension " @@ -775,7 +1944,7 @@ msgid "" "share these :c:type:`PyTypeObject` structures between extension modules." msgstr "" -#: ../../extending/newtypes_tutorial.rst:792 +#: ../../extending/newtypes_tutorial.rst:794 msgid "" "In this example we will create a :class:`!SubList` type that inherits from " "the built-in :class:`list` type. The new type will be completely compatible " @@ -783,34 +1952,148 @@ msgid "" "that increases an internal counter:" msgstr "" -#: ../../extending/newtypes_tutorial.rst:812 +#: ../../extending/newtypes_tutorial.rst:799 +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:811 +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" +" .ob_base = 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 int\n" +"sublist_module_exec(PyObject *m)\n" +"{\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"SubList\", (PyObject *) &SubListType) < " +"0) {\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}\n" +"\n" +"static PyModuleDef_Slot sublist_module_slots[] = {\n" +" {Py_mod_exec, sublist_module_exec},\n" +" {Py_mod_multiple_interpreters, " +"Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\n" +" {0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef sublist_module = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"sublist\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = 0,\n" +" .m_slots = sublist_module_slots,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_sublist(void)\n" +"{\n" +" return PyModuleDef_Init(&sublist_module);\n" +"}\n" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:814 msgid "" "As you can see, the source code closely resembles the :class:`!Custom` " "examples in previous sections. We will break down the main differences " "between them. ::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:820 +#: ../../extending/newtypes_tutorial.rst:817 +msgid "" +"typedef struct {\n" +" PyListObject list;\n" +" int state;\n" +"} SubListObject;" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:822 msgid "" "The primary difference for derived type objects is that the base type's " "object structure must be the first value. The base type will already " "include the :c:func:`PyObject_HEAD` at the beginning of its structure." msgstr "" -#: ../../extending/newtypes_tutorial.rst:824 +#: ../../extending/newtypes_tutorial.rst:826 msgid "" "When a Python object is a :class:`!SubList` instance, its ``PyObject *`` " "pointer can be safely cast to both ``PyListObject *`` and ``SubListObject " "*``::" msgstr "" -#: ../../extending/newtypes_tutorial.rst:836 +#: ../../extending/newtypes_tutorial.rst:829 +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:838 msgid "" "We see above how to call through to the :meth:`~object.__init__` method of " "the base type." msgstr "" -#: ../../extending/newtypes_tutorial.rst:839 +#: ../../extending/newtypes_tutorial.rst:841 msgid "" "This pattern is important when writing a type with custom :c:member:" "`~PyTypeObject.tp_new` and :c:member:`~PyTypeObject.tp_dealloc` members. " @@ -819,16 +2102,34 @@ msgid "" "the base class handle it by calling its own :c:member:`~PyTypeObject.tp_new`." msgstr "" -#: ../../extending/newtypes_tutorial.rst:845 +#: ../../extending/newtypes_tutorial.rst:847 msgid "" "The :c:type:`PyTypeObject` struct supports a :c:member:`~PyTypeObject." "tp_base` specifying the type's concrete base class. Due to cross-platform " "compiler issues, you can't fill that field directly with a reference to :c:" -"type:`PyList_Type`; it should be done later in the module initialization " -"function::" +"type:`PyList_Type`; it should be done in the :c:data:`Py_mod_exec` function::" +msgstr "" + +#: ../../extending/newtypes_tutorial.rst:853 +msgid "" +"static int\n" +"sublist_module_exec(PyObject *m)\n" +"{\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0) {\n" +" return -1;\n" +" }\n" +"\n" +" if (PyModule_AddObjectRef(m, \"SubList\", (PyObject *) &SubListType) < " +"0) {\n" +" return -1;\n" +" }\n" +"\n" +" return 0;\n" +"}" msgstr "" -#: ../../extending/newtypes_tutorial.rst:871 +#: ../../extending/newtypes_tutorial.rst:868 msgid "" "Before calling :c:func:`PyType_Ready`, the type structure must have the :c:" "member:`~PyTypeObject.tp_base` slot filled in. When we are deriving an " @@ -837,17 +2138,17 @@ msgid "" "from the base type will be inherited." msgstr "" -#: ../../extending/newtypes_tutorial.rst:877 +#: ../../extending/newtypes_tutorial.rst:874 msgid "" "After that, calling :c:func:`PyType_Ready` and adding the type object to the " "module is the same as with the basic :class:`!Custom` examples." msgstr "" -#: ../../extending/newtypes_tutorial.rst:882 +#: ../../extending/newtypes_tutorial.rst:879 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../extending/newtypes_tutorial.rst:883 +#: ../../extending/newtypes_tutorial.rst:880 msgid "" "This is true when we know that the object is a basic type, like a string or " "a float." @@ -855,13 +2156,13 @@ msgstr "" "Isso é verdade quando sabemos que o objeto é um tipo básico, como uma string " "ou um float." -#: ../../extending/newtypes_tutorial.rst:886 +#: ../../extending/newtypes_tutorial.rst:883 msgid "" "We relied on this in the :c:member:`~PyTypeObject.tp_dealloc` handler in " "this example, because our type doesn't support garbage collection." msgstr "" -#: ../../extending/newtypes_tutorial.rst:889 +#: ../../extending/newtypes_tutorial.rst:886 msgid "" "We now know that the first and last members are strings, so perhaps we could " "be less careful about decrementing their reference counts, however, we " @@ -877,7 +2178,7 @@ msgstr "" "podemos garantir que a desalocação de uma instância de uma subclasse de " "cadeias de caracteres não retornará aos nossos objetos." -#: ../../extending/newtypes_tutorial.rst:895 +#: ../../extending/newtypes_tutorial.rst:892 msgid "" "Also, even with our attributes restricted to strings instances, the user " "could pass arbitrary :class:`str` subclasses and therefore still create " diff --git a/extending/windows.po b/extending/windows.po index bc2cc9351..d57cd0b80 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..f5507ac39 100644 --- a/faq/design.po +++ b/faq/design.po @@ -1,38 +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 -# Fernando, 2021 -# Aline Balogh , 2021 -# Amanda Savluchinske , 2021 -# Alexsandro Matias de Almeida , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Adorilson Bezerra , 2024 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +57,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 +133,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 +177,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 +191,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 +358,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 +442,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 +485,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 +527,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 +550,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 +601,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 +626,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 +740,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 +774,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 +793,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 +812,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 +826,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 +1080,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 +1156,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 +1261,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 "" @@ -1156,9 +1335,9 @@ msgid "" "An appropriate testing discipline can help build large complex applications " "in Python as well as having interface specifications would. In fact, it can " "be better because an interface specification cannot test certain properties " -"of a program. For example, the :meth:`!list.append` method is expected to " +"of a program. For example, the :meth:`list.append` method is expected to " "add new elements to the end of some internal list; an interface " -"specification cannot test that your :meth:`!list.append` implementation will " +"specification cannot test that your :meth:`list.append` implementation will " "actually do this correctly, but it's trivial to check this property in a " "test suite." msgstr "" @@ -1166,9 +1345,9 @@ msgstr "" "grandes e complexas no Python, assim como ter especificações de interface. " "Na verdade, pode ser melhor porque uma especificação de interface não pode " "testar certas propriedades de um programa. Por exemplo, espera-se que o " -"método :meth:`!list.append` adicione novos elementos ao final de alguma " -"lista interna; uma especificação de interface não pode testar se sua " -"implementação :meth:`!list.append` realmente fará isso corretamente, mas é " +"método :meth:`list.append` adicione novos elementos ao final de alguma lista " +"interna; uma especificação de interface não pode testar se sua " +"implementação :meth:`list.append` realmente fará isso corretamente, mas é " "trivial verificar esta propriedade em um conjunto de testes." #: ../../faq/design.rst:597 @@ -1219,6 +1398,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 +1469,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 +1505,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 +1549,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 +1584,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 +1662,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 +1689,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 +1716,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 +1756,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..2854764e9 100644 --- a/faq/extending.po +++ b/faq/extending.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,41 +71,25 @@ 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 "" "There are a number of alternatives to writing your own C extensions, " -"depending on what you're trying to do." +"depending on what you're trying to do. :ref:`Recommended third party tools " +"` offer both simpler and more sophisticated approaches to " +"creating C and C++ extensions for Python." msgstr "" -"Há um número de alternativas para escrever suas próprias extensões em C, " -"dependendo daquilo que você está tentando fazer." +"Há diversas alternativas para escrever suas próprias extensões C, dependendo " +"do que você está tentando fazer. :ref:`Ferramentas recomendadas de terceiros " +"` oferecem abordagens mais simples e mais sofisticadas para " +"criar extensões C e C++ para Python." -#: ../../faq/extending.rst:44 -msgid "" -"`Cython `_ and its relative `Pyrex `_ are compilers that accept a " -"slightly modified form of Python and generate the corresponding C code. " -"Cython and Pyrex make it possible to write an extension without having to " -"learn Python's C API." -msgstr "" - -#: ../../faq/extending.rst:50 -msgid "" -"If you need to interface to some C or C++ library for which no Python " -"extension currently exists, you can try wrapping the library's data types " -"and functions with a tool such as `SWIG `_. `SIP " -"`__, `CXX `_ `Boost `_, or `Weave " -"`_ are also alternatives for wrapping C++ " -"libraries." -msgstr "" - -#: ../../faq/extending.rst:61 +#: ../../faq/extending.rst:46 msgid "How can I execute arbitrary Python statements from C?" msgstr "Como posso executar instruções arbitrárias de Python a partir de C?" -#: ../../faq/extending.rst:63 +#: ../../faq/extending.rst:48 msgid "" "The highest-level function to do this is :c:func:`PyRun_SimpleString` which " "takes a single string argument to be executed in the context of the module " @@ -118,46 +98,68 @@ 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 +#: ../../faq/extending.rst:57 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 +#: ../../faq/extending.rst:59 msgid "" "Call the function :c:func:`PyRun_String` from the previous question with the " "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 +#: ../../faq/extending.rst:65 msgid "How do I extract C values from a Python object?" msgstr "Como extraio valores em C a partir de um objeto Python?" -#: ../../faq/extending.rst:82 +#: ../../faq/extending.rst:67 msgid "" "That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size` " "returns its length and :c:func:`PyTuple_GetItem` returns the item at a " "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 +#: ../../faq/extending.rst:72 msgid "" "For bytes, :c:func:`PyBytes_Size` returns its length and :c:func:" "`PyBytes_AsStringAndSize` provides a pointer to its value and its length. " "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 +#: ../../faq/extending.rst:77 msgid "" "To test the type of an object, first make sure it isn't ``NULL``, and then " "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 +#: ../../faq/extending.rst:80 msgid "" "There is also a high-level API to Python objects which is provided by the so-" "called 'abstract' interface -- read ``Include/abstract.h`` for further " @@ -166,81 +168,190 @@ 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 +#: ../../faq/extending.rst:89 msgid "How do I use Py_BuildValue() to create a tuple of arbitrary length?" msgstr "" "Como posso utilizar Py_BuildValue() para criar uma tupla de comprimento " "arbitrário?" -#: ../../faq/extending.rst:106 +#: ../../faq/extending.rst:91 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 +#: ../../faq/extending.rst:95 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 +#: ../../faq/extending.rst:97 msgid "" "The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary " "method of an object. The parameters are the object, the name of the method " "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:121 +#: ../../faq/extending.rst:102 +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:106 msgid "" "This works for any object that has methods -- whether built-in or user-" "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 +#: ../../faq/extending.rst:109 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:135 +#: ../../faq/extending.rst:112 +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:120 msgid "" "Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the " "argument list, to call a function without arguments, pass \"()\" for the " "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 +#: ../../faq/extending.rst:127 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 +#: ../../faq/extending.rst:129 msgid "" "In Python code, define an object that supports the ``write()`` method. " "Assign this object to :data:`sys.stdout` and :data:`sys.stderr`. Call " "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 +#: ../../faq/extending.rst:134 msgid "The easiest way to do this is to use the :class:`io.StringIO` class:" -msgstr "" - -#: ../../faq/extending.rst:161 +msgstr "O jeito mais fácil de fazer isso é usar a classe :class:`io.StringIO`:" + +#: ../../faq/extending.rst:136 +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:146 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:182 +#: ../../faq/extending.rst:148 +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:167 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 +#: ../../faq/extending.rst:169 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:171 +msgid "module = PyImport_ImportModule(\"\");" +msgstr "module = PyImport_ImportModule(\"\");" -#: ../../faq/extending.rst:188 +#: ../../faq/extending.rst:173 msgid "" "If the module hasn't been imported yet (i.e. it is not yet present in :data:" "`sys.modules`), this initializes the module; otherwise it simply returns the " @@ -248,24 +359,37 @@ 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 +#: ../../faq/extending.rst:179 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:199 +#: ../../faq/extending.rst:182 +msgid "attr = PyObject_GetAttrString(module, \"\");" +msgstr "attr = PyObject_GetAttrString(module, \"\");" + +#: ../../faq/extending.rst:184 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 +#: ../../faq/extending.rst:189 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 +#: ../../faq/extending.rst:191 msgid "" "Depending on your requirements, there are many approaches. To do this " "manually, begin by reading :ref:`the \"Extending and Embedding\" document " @@ -274,66 +398,104 @@ 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 +#: ../../faq/extending.rst:197 msgid "For C++ libraries, see :ref:`c-wrapper-software`." -msgstr "" +msgstr "Para bibliotecas C++, veja :ref:`c-wrapper-software`." -#: ../../faq/extending.rst:216 +#: ../../faq/extending.rst:201 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 +#: ../../faq/extending.rst:203 msgid "" "Setup must end in a newline, if there is no newline there, the build process " "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 +#: ../../faq/extending.rst:209 msgid "How do I debug an extension?" -msgstr "" +msgstr "Como eu depuro uma extensão?" -#: ../../faq/extending.rst:226 +#: ../../faq/extending.rst:211 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 +#: ../../faq/extending.rst:214 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:216 +msgid "br _PyImport_LoadDynamicModule" +msgstr "br _PyImport_LoadDynamicModule" -#: ../../faq/extending.rst:235 +#: ../../faq/extending.rst:220 msgid "Then, when you run GDB:" +msgstr "Então, ao executar o GDB:" + +#: ../../faq/extending.rst:222 +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 +#: ../../faq/extending.rst:232 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 +#: ../../faq/extending.rst:234 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:237 +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:239 +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:242 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:244 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 +503,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:250 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:253 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 +526,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ém 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:260 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:262 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:268 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:270 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:273 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..a7456ce2d 100644 --- a/faq/general.po +++ b/faq/general.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-21 15:05+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +215,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." @@ -434,11 +430,11 @@ msgstr "Como faço para obter a documentação do Python?" #: ../../faq/general.rst:188 msgid "" "The standard documentation for the current stable version of Python is " -"available at https://docs.python.org/3/. PDF, plain text, and downloadable " +"available at https://docs.python.org/3/. EPUB, plain text, and downloadable " "HTML versions are also available at https://docs.python.org/3/download.html." msgstr "" "A documentação padrão para a versão atualmente estável do Python está " -"disponível em https://docs.python.org/3/. Em PDF, texto simples e versões " +"disponível em https://docs.python.org/3/. Em EPUB, texto simples e versões " "HTML para download também estão disponíveis em https://docs.python.org/3/" "download.html." @@ -691,17 +687,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 +906,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..018ebbcaf 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..5e76b4f83 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c1d919951 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..8c8edfbcd 100644 --- a/faq/library.po +++ b/faq/library.po @@ -1,32 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +103,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 +141,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 +165,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 +189,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 +209,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 +269,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 +333,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 +374,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 +460,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 +503,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 +574,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." @@ -513,7 +721,7 @@ msgstr "" "Em teoria, isso significa que uma contabilidade exata requer um entendimento " "exato da implementação do bytecode PVM. Na prática, isso significa que as " "operações em variáveis compartilhadas de tipos de dados integrados " -"(inteiros, listas, dicionarios, etc.) que \"parecem atômicas\" realmente são." +"(inteiros, listas, dicionários, etc.) que \"parecem atômicas\" realmente são." #: ../../faq/library.rst:377 msgid "" @@ -523,10 +731,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 +979,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 +1005,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 +1136,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 +1204,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 +1252,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 +1403,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..e4bcb5878 100644 --- a/faq/programming.po +++ b/faq/programming.po @@ -1,40 +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: -# 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +34,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 +54,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 +63,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 +75,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 +89,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 +118,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 +152,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 +162,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 +182,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 +193,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 +211,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 +236,7 @@ msgstr "`Nuitka `_ (Multiplataforma)" #: ../../faq/programming.rst:100 msgid "`PyInstaller `_ (Cross-platform)" -msgstr "" +msgstr "`PyInstaller `_ (Multiplataforma)" #: ../../faq/programming.rst:101 msgid "" @@ -254,7 +257,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 +271,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 +289,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 +314,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 +335,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 +361,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 +387,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 +395,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 +415,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 +440,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 +483,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 +526,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 +534,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 +584,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 +596,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 +610,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 +642,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 +690,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 +714,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 +746,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 +773,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 +806,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 +864,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 +890,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 +913,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 +927,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 +965,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 "" @@ -791,15 +980,37 @@ msgstr "" #: ../../faq/programming.rst:457 msgid "" -"After the call to :meth:`!append`, the content of the mutable object has " -"changed from ``[]`` to ``[10]``. Since both the variables refer to the same " -"object, using either name accesses the modified value ``[10]``." +"After the call to :meth:`~sequence.append`, the content of the mutable " +"object has 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:`~sequence.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 +1021,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 +1041,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 +1063,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 +1077,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 +1089,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 +1114,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 +1244,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 +1258,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 +1316,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 +1398,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 +1420,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 +1440,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 +1472,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 +1486,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 +1507,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 +1516,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 +1527,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 +1543,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 +1567,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 +1604,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 +1617,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 +1691,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 +1722,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 +1752,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 +1773,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 +1798,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 +1831,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 +1871,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 +1914,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 +1931,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 +1950,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 +2017,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 +2068,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 +2128,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 +2157,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 +2169,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 +2186,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 +2201,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 +2280,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 +2321,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 +2344,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 +2382,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 +2396,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 +2428,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 +2447,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 +2456,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 +2469,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 +2496,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 +2559,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 +2571,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 +2583,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 +2601,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 +2618,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 +2650,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 +2664,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 +2673,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 +2700,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 +2721,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 +2745,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 +2756,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 +2805,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 +2898,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 +2908,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 +2938,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 +2952,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 "" @@ -1984,14 +3014,42 @@ msgid "" "an :meth:`~object.__iadd__` magic method, it gets called when the ``+=`` " "augmented assignment is executed, and its return value is what gets used in " "the assignment statement; and (b) for lists, :meth:`!__iadd__` is equivalent " -"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 "" +"to calling :meth:`~sequence.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:`~sequence.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 +3057,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 +3088,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 +3108,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 +3130,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 +3172,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 +3186,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 +3204,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 +3229,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 +3255,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 +3269,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 +3339,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 +3404,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 +3416,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 +3453,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 +3469,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:1696 +#: ../../faq/programming.rst:1700 +msgid "" +"def getcount():\n" +" return C.count" +msgstr "" +"def getcount():\n" +" return C.count" + +#: ../../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 +3712,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 +3787,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 +3846,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 +3879,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 +3900,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 +3955,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: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:1936 +#: ../../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 presume que o *station_id* nunca muda. Se os atributos " +"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" +" \"Exemplo 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 +4462,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 +4479,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 +4493,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 +4508,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 +4580,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 +4707,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 +4781,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 +4789,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 +4855,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 +4881,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..9f1b9733e 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..925dc18b9 100644 --- a/glossary.po +++ b/glossary.po @@ -1,34 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -69,15 +61,18 @@ msgstr "" "correspondentes esquerdo e direito (parênteses, colchetes, chaves ou aspas " "triplas) ou após especificar um decorador." -#: ../../glossary.rst:24 -msgid "The :const:`Ellipsis` built-in constant." -msgstr "A constante embutida :const:`Ellipsis`." +#: ../../glossary.rst:26 +msgid "" +"The three dots form of the :ref:`Ellipsis ` object." +msgstr "" +"Os três pontos formam o objeto :ref:`Ellipsis ` " +"(reticências)." -#: ../../glossary.rst:25 +#: ../../glossary.rst:27 msgid "abstract base class" msgstr "classe base abstrata" -#: ../../glossary.rst:27 +#: ../../glossary.rst:29 msgid "" "Abstract base classes complement :term:`duck-typing` by providing a way to " "define interfaces when other techniques like :func:`hasattr` would be clumsy " @@ -90,23 +85,23 @@ 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`." - -#: ../../glossary.rst:38 +"Classes bases abstratas (ABCs, do inglês *abstract base class*) complementam " +"a :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:40 msgid "annotation" msgstr "anotação" -#: ../../glossary.rst:40 +#: ../../glossary.rst:42 msgid "" "A label associated with a variable, a class attribute or a function " "parameter or return value, used by convention as a :term:`type hint`." @@ -115,19 +110,19 @@ msgstr "" "função ou valor de retorno, usado por convenção como :term:`dica de tipo " "`." -#: ../../glossary.rst:44 +#: ../../glossary.rst:46 msgid "" "Annotations of local variables cannot be accessed at runtime, but " "annotations of global variables, class attributes, and functions are stored " "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." -#: ../../glossary.rst:50 +#: ../../glossary.rst:52 msgid "" "See :term:`variable annotation`, :term:`function annotation`, :pep:`484` " "and :pep:`526`, which describe this functionality. Also see :ref:" @@ -137,11 +132,11 @@ msgstr "" "pep:`526`, que descrevem esta funcionalidade. Veja também :ref:`annotations-" "howto` para as melhores práticas sobre como trabalhar com anotações." -#: ../../glossary.rst:54 +#: ../../glossary.rst:56 msgid "argument" msgstr "argumento" -#: ../../glossary.rst:56 +#: ../../glossary.rst:58 msgid "" "A value passed to a :term:`function` (or :term:`method`) when calling the " "function. There are two kinds of argument:" @@ -149,7 +144,7 @@ msgstr "" "Um valor passado para uma :term:`função` (ou :term:" "`método`) ao chamar a função. Existem dois tipos de argumento:" -#: ../../glossary.rst:59 +#: ../../glossary.rst:61 msgid "" ":dfn:`keyword argument`: an argument preceded by an identifier (e.g. " "``name=``) in a function call or passed as a value in a dictionary preceded " @@ -157,11 +152,19 @@ msgid "" "following calls to :func:`complex`::" msgstr "" ":dfn:`argumento nomeado`: um argumento precedido por um identificador (por " -"exemplo, ``name=``) na chamada de uma função ou passada como um valor em um " +"exemplo, ``name=``) na chamada de uma função ou passado como um valor em um " "dicionário precedido por ``**``. Por exemplo, ``3`` e ``5`` são ambos " -"argumentos nomeados na chamada da função :func:`complex` a seguir::" +"argumentos nomeados nas chamadas da função :func:`complex` a seguir::" -#: ../../glossary.rst:67 +#: ../../glossary.rst:66 +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:69 msgid "" ":dfn:`positional argument`: an argument that is not a keyword argument. " "Positional arguments can appear at the beginning of an argument list and/or " @@ -170,11 +173,19 @@ msgid "" msgstr "" ":dfn:`argumento posicional`: um argumento que não é um argumento nomeado. " "Argumentos posicionais podem aparecer no início da lista de argumentos e/ou " -"podem ser passados com elementos de um :term:`iterável` precedido " -"por ``*``. Por exemplo, ``3`` e ``5`` são ambos argumentos posicionais nas " +"podem ser passados como elementos de um :term:`iterável` precedidos por " +"``*``. Por exemplo, ``3`` e ``5`` são ambos argumentos posicionais nas " "chamadas a seguir::" -#: ../../glossary.rst:76 +#: ../../glossary.rst:75 +msgid "" +"complex(3, 5)\n" +"complex(*(3, 5))" +msgstr "" +"complex(3, 5)\n" +"complex(*(3, 5))" + +#: ../../glossary.rst:78 msgid "" "Arguments are assigned to the named local variables in a function body. See " "the :ref:`calls` section for the rules governing this assignment. " @@ -183,10 +194,10 @@ msgid "" msgstr "" "Argumentos são atribuídos às variáveis locais nomeadas no corpo da função. " "Veja a seção :ref:`calls` para as regras de atribuição. Sintaticamente, " -"qualquer expressão pode ser usada para representar um argumento; avaliada a " -"expressão, o valor é atribuído à variável local." +"qualquer expressão pode ser usada para representar um argumento; após a " +"expressão ser avaliada, o valor resultante é atribuído à variável local." -#: ../../glossary.rst:81 +#: ../../glossary.rst:83 msgid "" "See also the :term:`parameter` glossary entry, the FAQ question on :ref:`the " "difference between arguments and parameters `, " @@ -196,25 +207,25 @@ msgstr "" "ref:`a diferença entre argumentos e parâmetros ` " "e :pep:`362`." -#: ../../glossary.rst:84 +#: ../../glossary.rst:86 msgid "asynchronous context manager" msgstr "gerenciador de contexto assíncrono" -#: ../../glossary.rst:86 +#: ../../glossary.rst:88 msgid "" "An object which controls the environment seen in an :keyword:`async with` " "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 +#: ../../glossary.rst:91 msgid "asynchronous generator" msgstr "gerador assíncrono" -#: ../../glossary.rst:91 +#: ../../glossary.rst:93 msgid "" "A function which returns an :term:`asynchronous generator iterator`. It " "looks like a coroutine function defined with :keyword:`async def` except " @@ -226,7 +237,7 @@ msgstr "" "fato de conter instruções :keyword:`yield` para produzir uma série de " "valores que podem ser usados em um laço :keyword:`async for`." -#: ../../glossary.rst:96 +#: ../../glossary.rst:98 msgid "" "Usually refers to an asynchronous generator function, but may refer to an " "*asynchronous generator iterator* in some contexts. In cases where the " @@ -236,7 +247,7 @@ msgstr "" "a um *iterador gerador assíncrono* em alguns contextos. Em casos em que o " "significado não esteja claro, usar o termo completo evita a ambiguidade." -#: ../../glossary.rst:100 +#: ../../glossary.rst:102 msgid "" "An asynchronous generator function may contain :keyword:`await` expressions " "as well as :keyword:`async for`, and :keyword:`async with` statements." @@ -244,17 +255,17 @@ msgstr "" "Uma função geradora assíncrona pode conter expressões :keyword:`await` e " "também as instruções :keyword:`async for` e :keyword:`async with`." -#: ../../glossary.rst:103 +#: ../../glossary.rst:105 msgid "asynchronous generator iterator" msgstr "iterador gerador assíncrono" -#: ../../glossary.rst:105 -msgid "An object created by a :term:`asynchronous generator` function." +#: ../../glossary.rst:107 +msgid "An object created by an :term:`asynchronous generator` function." msgstr "" "Um objeto criado por uma função :term:`geradora assíncrona `." -#: ../../glossary.rst:107 +#: ../../glossary.rst:109 msgid "" "This is an :term:`asynchronous iterator` which when called using the :meth:" "`~object.__anext__` method returns an awaitable object which will execute " @@ -265,25 +276,25 @@ msgstr "" "meth:`~object.__anext__`, retorna um objeto aguardável que executará o corpo " "da função geradora assíncrona até a próxima expressão :keyword:`yield`." -#: ../../glossary.rst:112 +#: ../../glossary.rst:114 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`." -#: ../../glossary.rst:117 +#: ../../glossary.rst:119 msgid "asynchronous iterable" msgstr "iterável assíncrono" -#: ../../glossary.rst:119 +#: ../../glossary.rst:121 msgid "" "An object, that can be used in an :keyword:`async for` statement. Must " "return an :term:`asynchronous iterator` from its :meth:`~object.__aiter__` " @@ -293,11 +304,11 @@ msgstr "" "retornar um :term:`iterador assíncrono` do seu método :meth:`~object." "__aiter__`. Introduzido por :pep:`492`." -#: ../../glossary.rst:122 +#: ../../glossary.rst:124 msgid "asynchronous iterator" msgstr "iterador assíncrono" -#: ../../glossary.rst:124 +#: ../../glossary.rst:126 msgid "" "An object that implements the :meth:`~object.__aiter__` and :meth:`~object." "__anext__` methods. :meth:`~object.__anext__` must return an :term:" @@ -312,11 +323,11 @@ msgstr "" "até que ele levante uma exceção :exc:`StopAsyncIteration`. Introduzido pela :" "pep:`492`." -#: ../../glossary.rst:129 +#: ../../glossary.rst:131 msgid "attribute" msgstr "atributo" -#: ../../glossary.rst:131 +#: ../../glossary.rst:133 msgid "" "A value associated with an object which is usually referenced by name using " "dotted expressions. For example, if an object *o* has an attribute *a* it " @@ -326,7 +337,7 @@ msgstr "" "separado por um ponto. Por exemplo, se um objeto *o* tem um atributo *a* " "esse seria referenciado como *o.a*." -#: ../../glossary.rst:136 +#: ../../glossary.rst:138 msgid "" "It is possible to give an object an attribute whose name is not an " "identifier as defined by :ref:`identifiers`, for example using :func:" @@ -340,11 +351,11 @@ msgstr "" "expressão pontilhada e, em vez disso, precisaria ser recuperado com :func:" "`getattr`." -#: ../../glossary.rst:141 +#: ../../glossary.rst:143 msgid "awaitable" msgstr "aguardável" -#: ../../glossary.rst:143 +#: ../../glossary.rst:145 msgid "" "An object that can be used in an :keyword:`await` expression. Can be a :" "term:`coroutine` or an object with an :meth:`~object.__await__` method. See " @@ -354,11 +365,11 @@ msgstr "" "uma :term:`corrotina` ou um objeto com um método :meth:`~object.__await__`. " "Veja também a :pep:`492`." -#: ../../glossary.rst:146 +#: ../../glossary.rst:148 msgid "BDFL" msgstr "BDFL" -#: ../../glossary.rst:148 +#: ../../glossary.rst:150 msgid "" "Benevolent Dictator For Life, a.k.a. `Guido van Rossum `_, Python's creator." @@ -367,11 +378,11 @@ msgstr "" "Life\" (em português, \"Ditador Benevolente Vitalício\"), referindo-se a " "`Guido van Rossum `_, criador do Python." -#: ../../glossary.rst:150 +#: ../../glossary.rst:152 msgid "binary file" msgstr "arquivo binário" -#: ../../glossary.rst:152 +#: ../../glossary.rst:154 msgid "" "A :term:`file object` able to read and write :term:`bytes-like objects " "`. Examples of binary files are files opened in binary " @@ -380,12 +391,12 @@ msgid "" "BytesIO` and :class:`gzip.GzipFile`." msgstr "" "Um :term:`objeto arquivo ` capaz de ler e gravar em :term:" -"`objetos bytes ou similar `. Exemplos de arquivos " +"`objetos bytes ou similares `. Exemplos de arquivos " "binários são arquivos abertos no modo binário (``'rb'``, ``'wb'`` ou " "``'rb+'``), :data:`sys.stdin.buffer `, :data:`sys.stdout.buffer " "`, e instâncias de :class:`io.BytesIO` e :class:`gzip.GzipFile`." -#: ../../glossary.rst:159 +#: ../../glossary.rst:161 msgid "" "See also :term:`text file` for a file object able to read and write :class:" "`str` objects." @@ -393,11 +404,11 @@ msgstr "" "Veja também :term:`arquivo texto ` para um objeto arquivo capaz " "de ler e gravar em objetos :class:`str`." -#: ../../glossary.rst:161 +#: ../../glossary.rst:163 msgid "borrowed reference" msgstr "referência emprestada" -#: ../../glossary.rst:163 +#: ../../glossary.rst:165 msgid "" "In Python's C API, a borrowed reference is a reference to an object, where " "the code using the object does not own the reference. It becomes a dangling " @@ -409,7 +420,7 @@ msgstr "" "destruído. Por exemplo, uma coleta de lixo pode remover a última :term:" "`referência forte` para o objeto e assim destruí-lo." -#: ../../glossary.rst:169 +#: ../../glossary.rst:171 msgid "" "Calling :c:func:`Py_INCREF` on the :term:`borrowed reference` is recommended " "to convert it to a :term:`strong reference` in-place, except when the object " @@ -423,11 +434,11 @@ msgstr "" "emprestada. A função :c:func:`Py_NewRef` pode ser usada para criar uma nova :" "term:`referência forte`." -#: ../../glossary.rst:174 +#: ../../glossary.rst:176 msgid "bytes-like object" -msgstr "objeto byte ou similar" +msgstr "objeto bytes ou similar" -#: ../../glossary.rst:176 +#: ../../glossary.rst:178 msgid "" "An object that supports the :ref:`bufferobjects` and can export a C-:term:" "`contiguous` buffer. This includes all :class:`bytes`, :class:`bytearray`, " @@ -436,14 +447,14 @@ msgid "" "with binary data; these include compression, saving to a binary file, and " "sending over a socket." 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 " -"várias operações que funcionam com dados binários; isso inclui compactação, " +"Um objeto com suporte ao :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 bytes ou similares 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." -#: ../../glossary.rst:183 +#: ../../glossary.rst:185 msgid "" "Some operations need the binary data to be mutable. The documentation often " "refers to these as \"read-write bytes-like objects\". Example mutable " @@ -453,18 +464,19 @@ 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 similares " +"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 similares para somente leitura\"); exemplos " +"disso incluem :class:`bytes` e a :class:`memoryview` de um objeto :class:" +"`bytes`." -#: ../../glossary.rst:191 +#: ../../glossary.rst:193 msgid "bytecode" msgstr "bytecode" -#: ../../glossary.rst:193 +#: ../../glossary.rst:195 msgid "" "Python source code is compiled into bytecode, the internal representation of " "a Python program in the CPython interpreter. The bytecode is also cached in " @@ -485,7 +497,7 @@ msgstr "" "bytecodes sejam executados entre máquinas virtuais Python diferentes, nem " "que se mantenham estáveis entre versões de Python." -#: ../../glossary.rst:203 +#: ../../glossary.rst:205 msgid "" "A list of bytecode instructions can be found in the documentation for :ref:" "`the dis module `." @@ -493,11 +505,11 @@ msgstr "" "Uma lista de instruções bytecode pode ser encontrada na documentação para :" "ref:`o módulo dis `." -#: ../../glossary.rst:205 +#: ../../glossary.rst:207 msgid "callable" msgstr "chamável" -#: ../../glossary.rst:207 +#: ../../glossary.rst:209 msgid "" "A callable is an object that can be called, possibly with a set of arguments " "(see :term:`argument`), with the following syntax::" @@ -506,6 +518,10 @@ msgstr "" "de argumentos (veja :term:`argumento`), com a seguinte sintaxe::" #: ../../glossary.rst:212 +msgid "callable(argument1, argument2, argumentN)" +msgstr "chamavel(argumento1, argumento2, argumentoN)" + +#: ../../glossary.rst:214 msgid "" "A :term:`function`, and by extension a :term:`method`, is a callable. An " "instance of a class that implements the :meth:`~object.__call__` method is " @@ -515,11 +531,11 @@ msgstr "" "instância de uma classe que implementa o método :meth:`~object.__call__` " "também é um chamável." -#: ../../glossary.rst:215 +#: ../../glossary.rst:217 msgid "callback" msgstr "função de retorno" -#: ../../glossary.rst:217 +#: ../../glossary.rst:219 msgid "" "A subroutine function which is passed as an argument to be executed at some " "point in the future." @@ -527,11 +543,11 @@ msgstr "" "Também conhecida como callback, é uma função sub-rotina que é passada como " "um argumento a ser executado em algum ponto no futuro." -#: ../../glossary.rst:219 +#: ../../glossary.rst:221 msgid "class" msgstr "classe" -#: ../../glossary.rst:221 +#: ../../glossary.rst:223 msgid "" "A template for creating user-defined objects. Class definitions normally " "contain method definitions which operate on instances of the class." @@ -540,11 +556,11 @@ msgstr "" "classe normalmente contém definições de métodos que operam sobre instâncias " "da classe." -#: ../../glossary.rst:224 +#: ../../glossary.rst:226 msgid "class variable" msgstr "variável de classe" -#: ../../glossary.rst:226 +#: ../../glossary.rst:228 msgid "" "A variable defined in a class and intended to be modified only at class " "level (i.e., not in an instance of the class)." @@ -552,11 +568,72 @@ msgstr "" "Uma variável definida em uma classe e destinada a ser modificada apenas no " "nível da classe (ou seja, não em uma instância da classe)." -#: ../../glossary.rst:228 +#: ../../glossary.rst:230 +msgid "closure variable" +msgstr "variável de clausura" + +#: ../../glossary.rst:232 +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:237 +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:240 +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:248 +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:252 msgid "complex number" msgstr "número complexo" -#: ../../glossary.rst:230 +#: ../../glossary.rst:254 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 +657,89 @@ msgstr "" "sabe se irá precisar deles, é quase certo que você pode ignorá-los sem " "problemas." -#: ../../glossary.rst:240 +#: ../../glossary.rst:264 +msgid "context" +msgstr "contexto" + +#: ../../glossary.rst:266 +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:269 +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:271 +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:275 +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:277 +msgid "context management protocol" +msgstr "protocolo de gerenciamento de contexto" + +#: ../../glossary.rst:279 +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:281 msgid "context manager" msgstr "gerenciador de contexto" -#: ../../glossary.rst:242 +#: ../../glossary.rst:283 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:286 msgid "context variable" msgstr "variável de contexto" -#: ../../glossary.rst:247 +#: ../../glossary.rst:288 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:292 msgid "contiguous" msgstr "contíguo" -#: ../../glossary.rst:258 +#: ../../glossary.rst:296 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 +757,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:304 msgid "coroutine" msgstr "corrotina" -#: ../../glossary.rst:268 +#: ../../glossary.rst:306 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 +773,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:311 msgid "coroutine function" msgstr "função de corrotina" -#: ../../glossary.rst:275 +#: ../../glossary.rst:313 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 +789,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:318 msgid "CPython" msgstr "CPython" -#: ../../glossary.rst:282 +#: ../../glossary.rst:320 msgid "" "The canonical implementation of the Python programming language, as " "distributed on `python.org `_. The term \"CPython\" " @@ -684,11 +805,32 @@ msgstr "" "\"CPython\" é usado quando necessário distinguir esta implementação de " "outras como Jython ou IronPython." -#: ../../glossary.rst:286 +#: ../../glossary.rst:324 +msgid "current context" +msgstr "contexto atual" + +#: ../../glossary.rst:326 +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:332 msgid "decorator" msgstr "decorador" -#: ../../glossary.rst:288 +#: ../../glossary.rst:334 msgid "" "A function returning another function, usually applied as a function " "transformation using the ``@wrapper`` syntax. Common examples for " @@ -698,7 +840,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:338 msgid "" "The decorator syntax is merely syntactic sugar, the following two function " "definitions are semantically equivalent::" @@ -706,7 +848,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:341 +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:349 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 +876,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:352 msgid "descriptor" msgstr "descritor" -#: ../../glossary.rst:308 +#: ../../glossary.rst:354 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 +903,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:365 msgid "" "For more information about descriptors' methods, see :ref:`descriptors` or " "the :ref:`Descriptor How To Guide `." @@ -751,11 +911,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:367 msgid "dictionary" msgstr "dicionário" -#: ../../glossary.rst:323 +#: ../../glossary.rst:369 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 +925,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:373 msgid "dictionary comprehension" msgstr "compreensão de dicionário" -#: ../../glossary.rst:329 +#: ../../glossary.rst:375 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 +941,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:379 msgid "dictionary view" msgstr "visão de dicionário" -#: ../../glossary.rst:335 +#: ../../glossary.rst:381 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 +960,30 @@ msgstr "" "dicionário a se tornar uma lista completa use ``list(dictview)``. Veja :ref:" "`dict-views`." -#: ../../glossary.rst:341 +#: ../../glossary.rst:387 msgid "docstring" msgstr "docstring" -#: ../../glossary.rst:343 +#: ../../glossary.rst:389 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:395 msgid "duck-typing" msgstr "tipagem pato" -#: ../../glossary.rst:351 +#: ../../glossary.rst:397 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 +1007,25 @@ msgstr "" "class>`.) Ao invés disso, são normalmente empregados testes :func:`hasattr` " "ou programação :term:`EAFP`." -#: ../../glossary.rst:360 +#: ../../glossary.rst:406 +msgid "dunder" +msgstr "dunder" + +#: ../../glossary.rst:408 +msgid "" +"An informal short-hand for \"double underscore\", used when talking about a :" +"term:`special method`. For example, ``__init__`` is often pronounced " +"\"dunder init\"." +msgstr "" +"Uma abreviação informal para \"double underscore\" (em português, sublinhado " +"duplo), usada ao se referir a um :term:`método especial`. Por exemplo, " +"``__init__`` é frequentemente pronunciado como \"dunder init\"." + +#: ../../glossary.rst:411 msgid "EAFP" msgstr "EAFP" -#: ../../glossary.rst:362 +#: ../../glossary.rst:413 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 +1042,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:419 msgid "expression" msgstr "expressão" -#: ../../glossary.rst:370 +#: ../../glossary.rst:421 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 +1065,11 @@ msgstr "" "como, por exemplo, :keyword:`while`. Atribuições também são instruções, não " "expressões." -#: ../../glossary.rst:377 +#: ../../glossary.rst:428 msgid "extension module" msgstr "módulo de extensão" -#: ../../glossary.rst:379 +#: ../../glossary.rst:430 msgid "" "A module written in C or C++, using Python's C API to interact with the core " "and with user code." @@ -903,11 +1077,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:432 msgid "f-string" msgstr "f-string" -#: ../../glossary.rst:383 +#: ../../glossary.rst:434 msgid "" "String literals prefixed with ``'f'`` or ``'F'`` are commonly called \"f-" "strings\" which is short for :ref:`formatted string literals `. " @@ -917,11 +1091,11 @@ msgstr "" "strings\" que é uma abreviação de :ref:`formatted string literals `. Veja também :pep:`498`." -#: ../../glossary.rst:386 +#: ../../glossary.rst:437 msgid "file object" msgstr "objeto arquivo" -#: ../../glossary.rst:388 +#: ../../glossary.rst:439 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 +1112,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:447 msgid "" "There are actually three categories of file objects: raw :term:`binary files " "`, buffered :term:`binary files ` and :term:`text " @@ -952,19 +1126,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:452 msgid "file-like object" msgstr "objeto arquivo ou similar" -#: ../../glossary.rst:403 +#: ../../glossary.rst:454 msgid "A synonym for :term:`file object`." msgstr "Um sinônimo do termo :term:`objeto arquivo`." -#: ../../glossary.rst:404 +#: ../../glossary.rst:455 msgid "filesystem encoding and error handler" msgstr "tratador de erros e codificação do sistema de arquivos" -#: ../../glossary.rst:406 +#: ../../glossary.rst:457 msgid "" "Encoding and error handler used by Python to decode bytes from the operating " "system and encode Unicode to the operating system." @@ -972,7 +1146,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:460 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 +1157,7 @@ msgstr "" "arquivos falhar em fornecer essa garantia, as funções da API podem levantar :" "exc:`UnicodeError`." -#: ../../glossary.rst:413 +#: ../../glossary.rst:464 msgid "" "The :func:`sys.getfilesystemencoding` and :func:`sys." "getfilesystemencodeerrors` functions can be used to get the filesystem " @@ -993,7 +1167,7 @@ msgstr "" "getfilesystemencodeerrors` podem ser usadas para obter o tratador de erros e " "codificação do sistema de arquivos." -#: ../../glossary.rst:417 +#: ../../glossary.rst:468 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 +1179,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:473 msgid "See also the :term:`locale encoding`." msgstr "Veja também :term:`codificação da localidade`." -#: ../../glossary.rst:423 +#: ../../glossary.rst:474 msgid "finder" msgstr "localizador" -#: ../../glossary.rst:425 +#: ../../glossary.rst:476 msgid "" "An object that tries to find the :term:`loader` for a module that is being " "imported." @@ -1021,7 +1195,7 @@ msgstr "" "Um objeto que tenta encontrar o :term:`carregador` para um módulo que está " "sendo importado." -#: ../../glossary.rst:428 +#: ../../glossary.rst:479 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:483 +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:484 msgid "floor division" msgstr "divisão pelo piso" -#: ../../glossary.rst:435 +#: ../../glossary.rst:486 msgid "" "Mathematical division that rounds down to nearest integer. The floor " "division operator is ``//``. For example, the expression ``11 // 4`` " @@ -1053,11 +1229,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:491 msgid "free threading" msgstr "threads livres" -#: ../../glossary.rst:442 +#: ../../glossary.rst:493 msgid "" "A threading model where multiple threads can run Python bytecode " "simultaneously within the same interpreter. This is in contrast to the :" @@ -1069,11 +1245,31 @@ msgstr "" "`trava global do interpretador` que permite apenas uma thread por vez " "executar bytecode Python. Veja :pep:`703`." -#: ../../glossary.rst:446 +#: ../../glossary.rst:497 +msgid "free variable" +msgstr "variável livre" + +#: ../../glossary.rst:499 +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:504 msgid "function" msgstr "função" -#: ../../glossary.rst:448 +#: ../../glossary.rst:506 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 +1281,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:510 msgid "function annotation" msgstr "anotação de função" -#: ../../glossary.rst:454 +#: ../../glossary.rst:512 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:514 msgid "" "Function annotations are usually used for :term:`type hints `: " "for example, this function is expected to take two :class:`int` arguments " @@ -1103,11 +1299,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:519 +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:522 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:524 msgid "" "See :term:`variable annotation` and :pep:`484`, which describe this " "functionality. Also see :ref:`annotations-howto` for best practices on " @@ -1117,11 +1321,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:528 msgid "__future__" msgstr "__future__" -#: ../../glossary.rst:472 +#: ../../glossary.rst:530 msgid "" "A :ref:`future statement `, ``from __future__ import ``, " "directs the compiler to compile the current module using syntax or semantics " @@ -1138,11 +1342,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:538 +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:541 msgid "garbage collection" msgstr "coleta de lixo" -#: ../../glossary.rst:485 +#: ../../glossary.rst:543 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 +1369,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:548 ../../glossary.rst:549 msgid "generator" msgstr "gerador" -#: ../../glossary.rst:493 +#: ../../glossary.rst:551 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 +1386,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:556 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 +1396,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:559 msgid "generator iterator" msgstr "iterador gerador" -#: ../../glossary.rst:503 +#: ../../glossary.rst:561 msgid "An object created by a :term:`generator` function." msgstr "Um objeto criado por uma função :term:`geradora `." -#: ../../glossary.rst:505 +#: ../../glossary.rst:563 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:569 ../../glossary.rst:570 msgid "generator expression" msgstr "expressão geradora" -#: ../../glossary.rst:514 +#: ../../glossary.rst:572 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 +1433,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:577 +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:579 msgid "generic function" msgstr "função genérica" -#: ../../glossary.rst:523 +#: ../../glossary.rst:581 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 +1456,7 @@ msgstr "" "diferentes tipos. Qual implementação deverá ser usada durante a execução é " "determinada pelo algoritmo de despacho." -#: ../../glossary.rst:527 +#: ../../glossary.rst:585 msgid "" "See also the :term:`single dispatch` glossary entry, the :func:`functools." "singledispatch` decorator, and :pep:`443`." @@ -1241,11 +1464,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:587 msgid "generic type" msgstr "tipo genérico" -#: ../../glossary.rst:531 +#: ../../glossary.rst:589 msgid "" "A :term:`type` that can be parameterized; typically a :ref:`container " "class` such as :class:`list` or :class:`dict`. Used for :" @@ -1255,7 +1478,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:594 msgid "" "For more details, see :ref:`generic alias types`, :pep:" "`483`, :pep:`484`, :pep:`585`, and the :mod:`typing` module." @@ -1263,19 +1486,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:596 msgid "GIL" msgstr "GIL" -#: ../../glossary.rst:540 +#: ../../glossary.rst:598 msgid "See :term:`global interpreter lock`." msgstr "Veja :term:`trava global do interpretador`." -#: ../../glossary.rst:541 +#: ../../glossary.rst:599 msgid "global interpreter lock" msgstr "trava global do interpretador" -#: ../../glossary.rst:543 +#: ../../glossary.rst:601 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 " @@ -1290,10 +1513,10 @@ msgstr "" "a implementação do CPython ao fazer com que o modelo de objetos (incluindo " "tipos embutidos críticos como o :class:`dict`) ganhem segurança implícita " "contra acesso concorrente. Travar todo o interpretador facilita que o " -"interpretador em si seja multitarefa, às custas de muito do paralelismo já " -"provido por máquinas multiprocessador." +"interpretador em si seja multithread, às custas de muito do paralelismo já " +"provido por máquinas com multiprocessadores." -#: ../../glossary.rst:552 +#: ../../glossary.rst:610 msgid "" "However, some extension modules, either standard or third-party, are " "designed so as to release the GIL when doing computationally intensive tasks " @@ -1303,30 +1526,30 @@ msgstr "" "No entanto, alguns módulos de extensão, tanto da biblioteca padrão quanto de " "terceiros, são desenvolvidos de forma a liberar a GIL ao realizar tarefas " "computacionalmente muito intensas, como compactação ou cálculos de hash. " -"Além disso, a GIL é sempre liberado nas operações de E/S." +"Além disso, a GIL é sempre liberada nas operações de E/S." -#: ../../glossary.rst:557 +#: ../../glossary.rst:615 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:621 msgid "hash-based pyc" msgstr "pyc baseado em hash" -#: ../../glossary.rst:565 +#: ../../glossary.rst:623 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 +1559,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:626 msgid "hashable" msgstr "hasheável" -#: ../../glossary.rst:570 +#: ../../glossary.rst:628 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 +1576,7 @@ msgstr "" "Objetos hasheáveis que são comparados como iguais devem ter o mesmo valor de " "hash." -#: ../../glossary.rst:576 +#: ../../glossary.rst:634 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 +1585,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:637 msgid "" "Most of Python's immutable built-in objects are hashable; mutable containers " "(such as lists or dictionaries) are not; immutable containers (such as " @@ -1372,18 +1595,18 @@ msgid "" "value is derived from their :func:`id`." msgstr "" "A maioria dos objetos embutidos imutáveis do Python são hasheáveis; " -"containers mutáveis (tais como listas ou dicionários) não são; containers " +"contêineres mutáveis (tais como listas ou dicionários) não são; contêineres " "imutáveis (tais como tuplas e frozensets) são hasheáveis apenas se os seus " "elementos são hasheáveis. Objetos que são instâncias de classes definidas " "pelo usuário são hasheáveis por padrão. Todos eles comparam de forma " "desigual (exceto entre si mesmos), e o seu valor hash é derivado a partir do " "seu :func:`id`." -#: ../../glossary.rst:586 +#: ../../glossary.rst:644 msgid "IDLE" msgstr "IDLE" -#: ../../glossary.rst:588 +#: ../../glossary.rst:646 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 +1616,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:649 msgid "immortal" msgstr "imortal" -#: ../../glossary.rst:593 +#: ../../glossary.rst:651 msgid "" -"If an object is immortal, its reference count is never modified, and " -"therefore it is never deallocated." +"*Immortal objects* are a CPython implementation detail introduced in :pep:" +"`683`." msgstr "" -"Se um objeto é imortal, sua contagem de referências nunca é modificada, e " -"portanto ele nunca será desalocado." +"*Objetos imortais* são um detalhe da implementação do CPython introduzida " +"na :pep:`683`." -#: ../../glossary.rst:596 -msgid "" -"Built-in strings and singletons are immortal objects. For example, :const:" -"`True` and :const:`None` singletons are immmortal." -msgstr "" -"Strings embutidas e singletons são objetos imortais. Por exemplo, os " -"singletons :const:`True` e :const:`None` são imortais." - -#: ../../glossary.rst:599 +#: ../../glossary.rst:654 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:657 msgid "immutable" msgstr "imutável" -#: ../../glossary.rst:603 +#: ../../glossary.rst:659 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 +1656,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:664 msgid "import path" msgstr "caminho de importação" -#: ../../glossary.rst:610 +#: ../../glossary.rst:666 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 +1673,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:671 msgid "importing" msgstr "importação" -#: ../../glossary.rst:617 +#: ../../glossary.rst:673 msgid "" "The process by which Python code in one module is made available to Python " "code in another module." @@ -1468,11 +1685,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:675 msgid "importer" msgstr "importador" -#: ../../glossary.rst:621 +#: ../../glossary.rst:677 msgid "" "An object that both finds and loads a module; both a :term:`finder` and :" "term:`loader` object." @@ -1480,11 +1697,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:679 msgid "interactive" msgstr "interativo" -#: ../../glossary.rst:625 +#: ../../glossary.rst:681 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 +1719,11 @@ msgstr "" "do comando ``help(x)``). Para saber mais sobre modo interativo, veja :ref:" "`tut-interac`." -#: ../../glossary.rst:632 +#: ../../glossary.rst:688 msgid "interpreted" msgstr "interpretado" -#: ../../glossary.rst:634 +#: ../../glossary.rst:690 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 +1741,11 @@ msgstr "" "geralmente serem executados mais lentamente. Veja também :term:`interativo " "`." -#: ../../glossary.rst:641 +#: ../../glossary.rst:697 msgid "interpreter shutdown" msgstr "desligamento do interpretador" -#: ../../glossary.rst:643 +#: ../../glossary.rst:699 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 +1766,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:708 msgid "" "The main reason for interpreter shutdown is that the ``__main__`` module or " "the script being run has finished executing." @@ -1557,28 +1774,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:710 msgid "iterable" msgstr "iterável" -#: ../../glossary.rst:656 +#: ../../glossary.rst:712 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 arquivo `, 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` ." +"`sequência`." -#: ../../glossary.rst:664 +#: ../../glossary.rst:720 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 +1817,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:730 msgid "iterator" msgstr "iterador" -#: ../../glossary.rst:676 +#: ../../glossary.rst:732 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 +1854,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:747 msgid "More information can be found in :ref:`typeiter`." msgstr "Mais informações podem ser encontradas em :ref:`typeiter`." -#: ../../glossary.rst:695 +#: ../../glossary.rst:751 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 +1868,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:756 msgid "key function" msgstr "função chave" -#: ../../glossary.rst:702 +#: ../../glossary.rst:758 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 +1883,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:763 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 +1895,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:769 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 +1910,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:776 msgid "keyword argument" msgstr "argumento nomeado" -#: ../../glossary.rst:722 ../../glossary.rst:1021 +#: ../../glossary.rst:778 ../../glossary.rst:1093 msgid "See :term:`argument`." msgstr "Veja :term:`argumento`." -#: ../../glossary.rst:723 +#: ../../glossary.rst:779 msgid "lambda" msgstr "lambda" -#: ../../glossary.rst:725 +#: ../../glossary.rst:781 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 +1936,11 @@ msgstr "" "é avaliada quando a função é chamada. A sintaxe para criar uma função lambda " "é ``lambda [parameters]: expression``" -#: ../../glossary.rst:728 +#: ../../glossary.rst:784 msgid "LBYL" msgstr "LBYL" -#: ../../glossary.rst:730 +#: ../../glossary.rst:786 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 +1953,7 @@ msgstr "" "contrasta com a abordagem :term:`EAFP` e é caracterizada pela presença de " "muitas instruções :keyword:`if`." -#: ../../glossary.rst:735 +#: ../../glossary.rst:791 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 +1967,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:796 +msgid "lexical analyzer" +msgstr "analisador léxico" + +#: ../../glossary.rst:799 +msgid "Formal name for the *tokenizer*; see :term:`token`." +msgstr "Nome formal para o *tokenizador*; veja :term:`token`." + +#: ../../glossary.rst:800 msgid "list" msgstr "lista" -#: ../../glossary.rst:742 +#: ../../glossary.rst:802 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 +1989,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:805 msgid "list comprehension" msgstr "compreensão de lista" -#: ../../glossary.rst:747 +#: ../../glossary.rst:807 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 +2008,39 @@ msgstr "" "keyword:`if` é opcional. Se omitida, todos os elementos no ``range(256)`` " "serão processados." -#: ../../glossary.rst:753 +#: ../../glossary.rst:813 msgid "loader" msgstr "carregador" -#: ../../glossary.rst:755 +#: ../../glossary.rst:815 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:821 +msgid ":ref:`finders-and-loaders`" +msgstr ":ref:`finders-and-loaders`" -#: ../../glossary.rst:759 +#: ../../glossary.rst:822 +msgid ":class:`importlib.abc.Loader`" +msgstr ":class:`importlib.abc.Loader`" + +#: ../../glossary.rst:823 +msgid ":pep:`302`" +msgstr ":pep:`302`" + +#: ../../glossary.rst:824 msgid "locale encoding" msgstr "codificação da localidade" -#: ../../glossary.rst:761 +#: ../../glossary.rst:826 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 +2048,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:829 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:831 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:833 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:835 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:836 msgid "magic method" msgstr "método mágico" -#: ../../glossary.rst:775 +#: ../../glossary.rst:840 msgid "An informal synonym for :term:`special method`." msgstr "Um sinônimo informal para um :term:`método especial`." -#: ../../glossary.rst:776 +#: ../../glossary.rst:841 msgid "mapping" msgstr "mapeamento" -#: ../../glossary.rst:778 +#: ../../glossary.rst:843 msgid "" "A container object that supports arbitrary key lookups and implements the " "methods specified in the :class:`collections.abc.Mapping` or :class:" @@ -1854,18 +2091,18 @@ msgid "" "`collections.defaultdict`, :class:`collections.OrderedDict` and :class:" "`collections.Counter`." msgstr "" -"Um objeto contêiner que tem suporte a pesquisas de chave arbitrária e " -"implementa os métodos especificados nas :class:`collections.abc.Mapping` ou :" -"class:`collections.abc.MutableMapping` :ref:`classes base abstratas " -"`. Exemplos incluem :class:`dict`, :class:" -"`collections.defaultdict`, :class:`collections.OrderedDict` e :class:" +"Um objeto contêiner com suporte a pesquisas de chave arbitrária e que " +"implementa os métodos especificados nas :ref:`classes base abstratas " +"` :class:`collections.abc.Mapping` ou :" +"class:`collections.abc.MutableMapping`. Exemplos incluem :class:`dict`, :" +"class:`collections.defaultdict`, :class:`collections.OrderedDict` e :class:" "`collections.Counter`." -#: ../../glossary.rst:784 +#: ../../glossary.rst:849 msgid "meta path finder" msgstr "localizador de metacaminho" -#: ../../glossary.rst:786 +#: ../../glossary.rst:851 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:855 msgid "" "See :class:`importlib.abc.MetaPathFinder` for the methods that meta path " "finders implement." @@ -1883,11 +2120,11 @@ msgstr "" "Veja :class:`importlib.abc.MetaPathFinder` para os métodos que localizadores " "de metacaminho implementam." -#: ../../glossary.rst:792 +#: ../../glossary.rst:857 msgid "metaclass" msgstr "metaclasse" -#: ../../glossary.rst:794 +#: ../../glossary.rst:859 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 +2147,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:869 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:838 ../../glossary.rst:870 ../../glossary.rst:1244 msgid "method" msgstr "método" -#: ../../glossary.rst:807 +#: ../../glossary.rst:872 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 +2167,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:876 msgid "method resolution order" msgstr "ordem de resolução de métodos" -#: ../../glossary.rst:813 +#: ../../glossary.rst:878 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 +2181,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:881 msgid "module" msgstr "módulo" -#: ../../glossary.rst:818 +#: ../../glossary.rst:883 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 +2196,15 @@ msgstr "" "módulos são carregados pelo Python através do processo de :term:" "`importação`." -#: ../../glossary.rst:822 +#: ../../glossary.rst:887 msgid "See also :term:`package`." msgstr "Veja também :term:`pacote`." -#: ../../glossary.rst:823 +#: ../../glossary.rst:888 msgid "module spec" -msgstr "especificação do módulo" +msgstr "spec de módulo" -#: ../../glossary.rst:825 +#: ../../glossary.rst:890 msgid "" "A namespace containing the import-related information used to load a module. " "An instance of :class:`importlib.machinery.ModuleSpec`." @@ -1976,19 +2213,23 @@ msgstr "" "usadas para carregar um módulo. Uma instância de :class:`importlib.machinery." "ModuleSpec`." -#: ../../glossary.rst:827 +#: ../../glossary.rst:893 +msgid "See also :ref:`module-specs`." +msgstr "Veja também :ref:`module-specs`." + +#: ../../glossary.rst:894 msgid "MRO" msgstr "MRO" -#: ../../glossary.rst:829 +#: ../../glossary.rst:896 msgid "See :term:`method resolution order`." msgstr "Veja :term:`ordem de resolução de métodos`." -#: ../../glossary.rst:830 +#: ../../glossary.rst:897 msgid "mutable" msgstr "mutável" -#: ../../glossary.rst:832 +#: ../../glossary.rst:899 msgid "" "Mutable objects can change their value but keep their :func:`id`. See also :" "term:`immutable`." @@ -1996,11 +2237,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:901 msgid "named tuple" msgstr "tupla nomeada" -#: ../../glossary.rst:836 +#: ../../glossary.rst:903 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 +2251,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:907 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 +2261,23 @@ msgstr "" "retornados por :func:`time.localtime` e :func:`os.stat`. Outro exemplo é :" "data:`sys.float_info`::" -#: ../../glossary.rst:851 +#: ../../glossary.rst:911 +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:918 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 +2296,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:926 msgid "namespace" msgstr "espaço de nomes" -#: ../../glossary.rst:861 +#: ../../glossary.rst:928 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 +2323,46 @@ msgstr "" "claro que estas funções são implementadas pelos módulos :mod:`random` e :mod:" "`itertools` respectivamente." -#: ../../glossary.rst:871 +#: ../../glossary.rst:938 msgid "namespace package" msgstr "pacote de espaço de nomes" -#: ../../glossary.rst:873 +#: ../../glossary.rst:940 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:945 +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:948 +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:950 msgid "See also :term:`module`." msgstr "Veja também :term:`módulo`." -#: ../../glossary.rst:879 +#: ../../glossary.rst:951 msgid "nested scope" msgstr "escopo aninhado" -#: ../../glossary.rst:881 +#: ../../glossary.rst:953 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 +2379,11 @@ msgstr "" "escrever para o espaço de nomes global. O :keyword:`nonlocal` permite " "escrita para escopos externos." -#: ../../glossary.rst:888 +#: ../../glossary.rst:960 msgid "new-style class" msgstr "classe estilo novo" -#: ../../glossary.rst:890 +#: ../../glossary.rst:962 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, " @@ -2119,16 +2391,16 @@ msgid "" "meth:`~object.__getattribute__`, class methods, and static methods." msgstr "" "Antigo nome para o tipo de classes agora usado para todos os objetos de " -"classes. Em versões anteriores do Python, apenas classes estilo podiam usar " -"recursos novos e versáteis do Python, tais como :attr:`~object.__slots__`, " -"descritores, propriedades, :meth:`~object.__getattribute__`, métodos de " -"classe, e métodos estáticos." +"classes. Em versões anteriores do Python, apenas classes estilo novo podiam " +"usar recursos novos e versáteis do Python, tais como :attr:`~object." +"__slots__`, descritores, propriedades, :meth:`~object.__getattribute__`, " +"métodos de classe e métodos estáticos." -#: ../../glossary.rst:895 +#: ../../glossary.rst:967 msgid "object" msgstr "objeto" -#: ../../glossary.rst:897 +#: ../../glossary.rst:969 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 +2409,11 @@ msgstr "" "definidos (métodos). Também a última classe base de qualquer :term:`classe " "estilo novo`." -#: ../../glossary.rst:900 +#: ../../glossary.rst:972 msgid "optimized scope" msgstr "escopo otimizado" -#: ../../glossary.rst:902 +#: ../../glossary.rst:974 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 +2432,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:981 msgid "package" msgstr "pacote" -#: ../../glossary.rst:911 +#: ../../glossary.rst:983 msgid "" "A Python :term:`module` which can contain submodules or recursively, " "subpackages. Technically, a package is a Python module with a ``__path__`` " @@ -2174,16 +2446,16 @@ msgstr "" "subpacotes. Tecnicamente, um pacote é um módulo Python com um atributo " "``__path__``." -#: ../../glossary.rst:915 +#: ../../glossary.rst:987 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:988 msgid "parameter" msgstr "parâmetro" -#: ../../glossary.rst:918 +#: ../../glossary.rst:990 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 +2465,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:994 msgid "" ":dfn:`positional-or-keyword`: specifies an argument that can be passed " "either :term:`positionally ` or as a :term:`keyword argument " @@ -2204,7 +2476,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:999 +msgid "def func(foo, bar=None): ..." +msgstr "def func(foo, bar=None): ..." + +#: ../../glossary.rst:1003 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 +2490,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:940 +#: ../../glossary.rst:1008 +msgid "def func(posonly1, posonly2, /, positional_or_keyword): ..." +msgstr "def func(somentepos1, somentepos2, /, posicional_ou_nomeado): ..." + +#: ../../glossary.rst:1012 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 +2507,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:1018 +msgid "def func(arg, *, kw_only1, kw_only2): ..." +msgstr "def func(arg, *, somente_nom1, somente_nom2): ..." + +#: ../../glossary.rst:1020 msgid "" ":dfn:`var-positional`: specifies that an arbitrary sequence of positional " "arguments can be provided (in addition to any positional arguments already " @@ -2243,7 +2527,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:1026 +msgid "def func(*args, **kwargs): ..." +msgstr "def func(*args, **kwargs): ..." + +#: ../../glossary.rst:1028 msgid "" ":dfn:`var-keyword`: specifies that arbitrarily many keyword arguments can be " "provided (in addition to any keyword arguments already accepted by other " @@ -2252,10 +2540,10 @@ msgid "" msgstr "" ":dfn:`var-nomeado`: especifica que, arbitrariamente, muitos argumentos " "nomeados podem ser fornecidos (em adição a qualquer argumento nomeado já " -"aceito por outros parâmetros). Tal parâmetro pode definido colocando-se " -"``**`` antes do nome, por exemplo *kwargs* no exemplo acima." +"aceito por outros parâmetros). Tal parâmetro pode ser definido colocando-se " +"``**`` antes do nome, por exemplo, *kwargs* no exemplo acima." -#: ../../glossary.rst:962 +#: ../../glossary.rst:1034 msgid "" "Parameters can specify both optional and required arguments, as well as " "default values for some optional arguments." @@ -2263,22 +2551,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:1037 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:1041 msgid "path entry" msgstr "entrada de caminho" -#: ../../glossary.rst:971 +#: ../../glossary.rst:1043 msgid "" "A single location on the :term:`import path` which the :term:`path based " "finder` consults to find modules for importing." @@ -2286,11 +2574,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:1045 msgid "path entry finder" msgstr "localizador de entrada de caminho" -#: ../../glossary.rst:975 +#: ../../glossary.rst:1047 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 +2588,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:1051 msgid "" "See :class:`importlib.abc.PathEntryFinder` for the methods that path entry " "finders implement." @@ -2308,11 +2596,11 @@ msgstr "" "Veja :class:`importlib.abc.PathEntryFinder` para os métodos que " "localizadores de entrada de caminho implementam." -#: ../../glossary.rst:981 +#: ../../glossary.rst:1053 msgid "path entry hook" msgstr "gancho de entrada de caminho" -#: ../../glossary.rst:983 +#: ../../glossary.rst:1055 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 +2610,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:1058 msgid "path based finder" msgstr "localizador baseado no caminho" -#: ../../glossary.rst:988 +#: ../../glossary.rst:1060 msgid "" "One of the default :term:`meta path finders ` which " "searches an :term:`import path` for modules." @@ -2334,11 +2622,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:1062 msgid "path-like object" msgstr "objeto caminho ou similar" -#: ../../glossary.rst:992 +#: ../../glossary.rst:1064 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 +2646,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:1072 msgid "PEP" msgstr "PEP" -#: ../../glossary.rst:1002 +#: ../../glossary.rst:1074 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 +2662,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:1080 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 +2676,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:1086 msgid "See :pep:`1`." msgstr "Veja :pep:`1`." -#: ../../glossary.rst:1015 +#: ../../glossary.rst:1087 msgid "portion" msgstr "porção" -#: ../../glossary.rst:1017 +#: ../../glossary.rst:1089 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 +2693,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:1091 msgid "positional argument" msgstr "argumento posicional" -#: ../../glossary.rst:1022 +#: ../../glossary.rst:1094 msgid "provisional API" msgstr "API provisória" -#: ../../glossary.rst:1024 +#: ../../glossary.rst:1096 msgid "" "A provisional API is one which has been deliberately excluded from the " "standard library's backwards compatibility guarantees. While major changes " @@ -2432,7 +2720,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:1105 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 +2731,7 @@ msgstr "" "encontrar uma resolução retroativa compatível para quaisquer problemas " "encontrados." -#: ../../glossary.rst:1037 +#: ../../glossary.rst:1109 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 +2741,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:1112 msgid "provisional package" msgstr "pacote provisório" -#: ../../glossary.rst:1042 +#: ../../glossary.rst:1114 msgid "See :term:`provisional API`." msgstr "Veja :term:`API provisória`." -#: ../../glossary.rst:1043 +#: ../../glossary.rst:1115 msgid "Python 3000" msgstr "Python 3000" -#: ../../glossary.rst:1045 +#: ../../glossary.rst:1117 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 +2763,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:1120 msgid "Pythonic" msgstr "Pythônico" -#: ../../glossary.rst:1050 +#: ../../glossary.rst:1122 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 +2776,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:1129 +msgid "" +"for i in range(len(food)):\n" +" print(food[i])" +msgstr "" +"for i in range(len(comida)):\n" +" print(comida[i])" + +#: ../../glossary.rst:1132 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:1064 +#: ../../glossary.rst:1134 +msgid "" +"for piece in food:\n" +" print(piece)" +msgstr "" +"for parte in comida:\n" +" print(parte)" + +#: ../../glossary.rst:1136 msgid "qualified name" msgstr "nome qualificado" -#: ../../glossary.rst:1066 +#: ../../glossary.rst:1138 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 +2821,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:1143 +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:1155 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 +2857,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:1159 +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:1162 msgid "reference count" msgstr "contagem de referências" -#: ../../glossary.rst:1092 +#: ../../glossary.rst:1164 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 +2890,21 @@ msgstr "" "função :func:`sys.getrefcount` para retornar a contagem de referências para " "um objeto específico." -#: ../../glossary.rst:1100 +#: ../../glossary.rst:1173 +msgid "" +"In :term:`CPython`, reference counts are not considered to be stable or well-" +"defined values; the number of references to an object, and how that number " +"is affected by Python code, may be different between versions." +msgstr "" +"Em :term:`CPython`, as contagens de referências não são consideradas valores " +"estáveis ou bem definidos; o número de referências a um objeto e como esse " +"número é afetado pelo código Python pode ser diferente entre as versões." + +#: ../../glossary.rst:1177 msgid "regular package" msgstr "pacote regular" -#: ../../glossary.rst:1102 +#: ../../glossary.rst:1179 msgid "" "A traditional :term:`package`, such as a directory containing an ``__init__." "py`` file." @@ -2561,15 +2912,15 @@ msgstr "" "Um :term:`pacote` tradicional, como um diretório contendo um arquivo " "``__init__.py``." -#: ../../glossary.rst:1105 +#: ../../glossary.rst:1182 msgid "See also :term:`namespace package`." msgstr "Veja também :term:`pacote de espaço de nomes`." -#: ../../glossary.rst:1106 +#: ../../glossary.rst:1183 msgid "REPL" msgstr "REPL" -#: ../../glossary.rst:1108 +#: ../../glossary.rst:1185 msgid "" "An acronym for the \"read–eval–print loop\", another name for the :term:" "`interactive` interpreter shell." @@ -2577,11 +2928,11 @@ msgstr "" "Um acrônimo para \"read–eval–print loop\", outro nome para o console :term:" "`interativo` do interpretador." -#: ../../glossary.rst:1110 +#: ../../glossary.rst:1187 msgid "__slots__" msgstr "__slots__" -#: ../../glossary.rst:1112 +#: ../../glossary.rst:1189 msgid "" "A declaration inside a class that saves memory by pre-declaring space for " "instance attributes and eliminating instance dictionaries. Though popular, " @@ -2595,11 +2946,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:1194 msgid "sequence" msgstr "sequência" -#: ../../glossary.rst:1119 +#: ../../glossary.rst:1196 msgid "" "An :term:`iterable` which supports efficient element access using integer " "indices via the :meth:`~object.__getitem__` special method and defines a :" @@ -2607,8 +2958,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,31 +2968,32 @@ 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:1205 msgid "" "The :class:`collections.abc.Sequence` abstract base class defines a much " "richer interface that goes beyond just :meth:`~object.__getitem__` and :meth:" -"`~object.__len__`, adding :meth:`!count`, :meth:`!index`, :meth:`~object." -"__contains__`, and :meth:`~object.__reversed__`. Types that implement this " -"expanded interface can be registered explicitly using :func:`~abc.ABCMeta." -"register`. For more documentation on sequence methods generally, see :ref:" -"`Common Sequence Operations `." +"`~object.__len__`, adding :meth:`~sequence.count`, :meth:`~sequence.index`, :" +"meth:`~object.__contains__`, and :meth:`~object.__reversed__`. Types that " +"implement this expanded interface can be registered explicitly using :func:" +"`~abc.ABCMeta.register`. For more documentation on sequence methods " +"generally, see :ref:`Common Sequence Operations `." msgstr "" "A classe base abstrata :class:`collections.abc.Sequence` define uma " "interface mais rica que vai além de apenas :meth:`~object.__getitem__` e :" -"meth:`~object.__len__`, adicionando :meth:`!count`, :meth:`!index`, :meth:" -"`~object.__contains__`, e :meth:`~object.__reversed__`. Tipos que " -"implementam essa interface podem ser explicitamente registrados usando :func:" -"`~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 +"meth:`~object.__len__`, adicionando :meth:`~sequence.count`, :meth:" +"`~sequence.index`, :meth:`~object.__contains__`, e :meth:`~object." +"__reversed__`. Tipos que implementam essa interface podem ser explicitamente " +"registrados usando :func:`~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:1215 msgid "set comprehension" msgstr "compreensão de conjunto" -#: ../../glossary.rst:1139 +#: ../../glossary.rst:1217 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 +3005,11 @@ msgstr "" "'abracadabra' if c not in 'abc'}`` gera um conjunto de strings ``{'r', 'd'}" "``. Veja :ref:`comprehensions`." -#: ../../glossary.rst:1143 +#: ../../glossary.rst:1221 msgid "single dispatch" msgstr "despacho único" -#: ../../glossary.rst:1145 +#: ../../glossary.rst:1223 msgid "" "A form of :term:`generic function` dispatch where the implementation is " "chosen based on the type of a single argument." @@ -2665,11 +3017,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:1225 msgid "slice" msgstr "fatia" -#: ../../glossary.rst:1149 +#: ../../glossary.rst:1227 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 +3033,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:1231 msgid "soft deprecated" msgstr "suavemente descontinuado" -#: ../../glossary.rst:1155 +#: ../../glossary.rst:1233 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:1237 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." -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." - -#: ../../glossary.rst:1164 -msgid "Another difference is that a soft deprecation does not issue a warning." +"Soft deprecation, unlike normal deprecation, does not plan on removing the " +"API and will not emit warnings." msgstr "" -"Uma outra diferença é que a descontinuação suave não provoca um alerta." +"A descontinuação suave, diferentemente da descontinuação normal, não planeja " +"remover a API e não emitirá avisos." -#: ../../glossary.rst:1166 +#: ../../glossary.rst:1240 msgid "" "See `PEP 387: Soft Deprecation `_." @@ -2720,11 +3063,11 @@ msgstr "" "Veja `PEP 387: Descontinuação suave `_." -#: ../../glossary.rst:1168 +#: ../../glossary.rst:1242 msgid "special method" msgstr "método especial" -#: ../../glossary.rst:1172 +#: ../../glossary.rst:1246 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 +3079,37 @@ msgstr "" "iniciando e terminando com dois underscores. Métodos especiais estão " "documentados em :ref:`specialnames`." -#: ../../glossary.rst:1176 +#: ../../glossary.rst:1250 +msgid "standard library" +msgstr "biblioteca padrão" + +#: ../../glossary.rst:1252 +msgid "" +"The collection of :term:`packages `, :term:`modules ` and :" +"term:`extension modules ` distributed as a part of the " +"official Python interpreter package. The exact membership of the collection " +"may vary based on platform, available system libraries, or other criteria. " +"Documentation can be found at :ref:`library-index`." +msgstr "" +"A coleção de :term:`pacotes `, :term:`módulos ` e :term:" +"`módulos de extensão` distribuída como parte do pacote do " +"interpretador Python oficial. A relação exata de elementos da coleção pode " +"variar de acordo com a plataforma, bibliotecas de sistema disponíveis ou " +"outros critérios. A documentação pode ser encontrada em :ref:`library-index`." + +#: ../../glossary.rst:1258 +msgid "" +"See also :data:`sys.stdlib_module_names` for a list of all possible standard " +"library module names." +msgstr "" +"Veja também :data:`sys.stdlib_module_names` para obter uma lista de todos os " +"possíveis nomes de módulos da biblioteca padrão." + +#: ../../glossary.rst:1260 msgid "statement" msgstr "instrução" -#: ../../glossary.rst:1178 +#: ../../glossary.rst:1262 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,25 +3119,35 @@ 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:1265 msgid "static type checker" msgstr "verificador de tipo estático" -#: ../../glossary.rst:1183 +#: ../../glossary.rst:1267 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 :" "mod:`typing` module." msgstr "" -"Uma ferramenta externa que lê o código Python e o analisa, procurando por " +"Uma ferramenta externa que lê código Python e o analisa, procurando por " "problemas como tipos incorretos. Consulte também :term:`dicas de tipo ` e o módulo :mod:`typing`." -#: ../../glossary.rst:1186 +#: ../../glossary.rst:1270 +msgid "stdlib" +msgstr "stdlib" + +#: ../../glossary.rst:1272 +msgid "An abbreviation of :term:`standard library`." +msgstr "" +"Uma abreviação para o termo :term:`biblioteca padrão` em inglês (standard " +"library)." + +#: ../../glossary.rst:1273 msgid "strong reference" msgstr "referência forte" -#: ../../glossary.rst:1188 +#: ../../glossary.rst:1275 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 +3159,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:1281 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 +3171,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:1286 msgid "See also :term:`borrowed reference`." msgstr "Veja também :term:`referência emprestada`." -#: ../../glossary.rst:1200 +#: ../../glossary.rst:1287 msgid "text encoding" msgstr "codificador de texto" -#: ../../glossary.rst:1202 +#: ../../glossary.rst:1289 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 +3189,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:1293 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 +3198,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:1296 msgid "" "There are a variety of different text serialization :ref:`codecs `, which are collectively referred to as \"text encodings\"." @@ -2827,11 +3206,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:1299 msgid "text file" msgstr "arquivo texto" -#: ../../glossary.rst:1214 +#: ../../glossary.rst:1301 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 +3225,41 @@ msgstr "" "``'w'``), :data:`sys.stdin`, :data:`sys.stdout`, e instâncias de :class:`io." "StringIO`." -#: ../../glossary.rst:1221 +#: ../../glossary.rst:1308 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 similares `." -#: ../../glossary.rst:1223 +#: ../../glossary.rst:1310 +msgid "token" +msgstr "token" + +#: ../../glossary.rst:1313 +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:1318 +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:1321 msgid "triple-quoted string" msgstr "aspas triplas" -#: ../../glossary.rst:1225 +#: ../../glossary.rst:1323 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 +3277,73 @@ msgstr "" "caractere de continuação, fazendo-as especialmente úteis quando escrevemos " "documentação em docstrings." -#: ../../glossary.rst:1232 +#: ../../glossary.rst:1330 msgid "type" msgstr "tipo" -#: ../../glossary.rst:1234 +#: ../../glossary.rst:1332 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:1336 msgid "type alias" -msgstr "tipo alias" +msgstr "apelido de tipo" -#: ../../glossary.rst:1240 +#: ../../glossary.rst:1338 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:1340 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:1343 +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:1347 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:1349 +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:1354 ../../glossary.rst:1368 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:1355 msgid "type hint" msgstr "dica de tipo" -#: ../../glossary.rst:1259 +#: ../../glossary.rst:1357 msgid "" "An :term:`annotation` that specifies the expected type for a variable, a " "class attribute, or a function parameter or return value." @@ -2928,7 +3351,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:1360 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 +3361,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:1364 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 +3370,11 @@ msgstr "" "não de variáveis locais, podem ser acessadas usando :func:`typing." "get_type_hints`." -#: ../../glossary.rst:1271 +#: ../../glossary.rst:1369 msgid "universal newlines" msgstr "novas linhas universais" -#: ../../glossary.rst:1273 +#: ../../glossary.rst:1371 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 +3388,30 @@ msgstr "" "no Macintosh ``'\\r'``. Veja :pep:`278` e :pep:`3116`, bem como :func:`bytes." "splitlines` para uso adicional." -#: ../../glossary.rst:1278 +#: ../../glossary.rst:1376 msgid "variable annotation" msgstr "anotação de variável" -#: ../../glossary.rst:1280 +#: ../../glossary.rst:1378 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:1380 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:1382 +msgid "" +"class C:\n" +" field: 'annotation'" +msgstr "" +"class C:\n" +" campo: 'anotação'" + +#: ../../glossary.rst:1385 msgid "" "Variable annotations are usually used for :term:`type hints `: " "for example this variable is expected to take :class:`int` values::" @@ -2989,12 +3420,16 @@ msgstr "" "`: por exemplo, espera-se que esta variável receba valores do " "tipo :class:`int`::" -#: ../../glossary.rst:1293 +#: ../../glossary.rst:1389 +msgid "count: int = 0" +msgstr "contagem: int = 0" + +#: ../../glossary.rst:1391 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:1393 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 +3439,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:1397 msgid "virtual environment" msgstr "ambiente virtual" -#: ../../glossary.rst:1301 +#: ../../glossary.rst:1399 msgid "" "A cooperatively isolated runtime environment that allows Python users and " "applications to install and upgrade Python distribution packages without " @@ -3019,15 +3454,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:1404 msgid "See also :mod:`venv`." msgstr "Veja também :mod:`venv`." -#: ../../glossary.rst:1307 +#: ../../glossary.rst:1405 msgid "virtual machine" msgstr "máquina virtual" -#: ../../glossary.rst:1309 +#: ../../glossary.rst:1407 msgid "" "A computer defined entirely in software. Python's virtual machine executes " "the :term:`bytecode` emitted by the bytecode compiler." @@ -3035,11 +3470,25 @@ 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:1409 +msgid "walrus operator" +msgstr "operador morsa" + +#: ../../glossary.rst:1411 +msgid "" +"A light-hearted way to refer to the :ref:`assignment expression ` operator ``:=`` because it looks a bit like a walrus if you " +"turn your head." +msgstr "" +"Uma maneira bem-humorada de se referir ao operador da :ref:`expressão de " +"atribuição ` ``:=`` porque ele se parece um pouco " +"com uma morsa se você virar a cabeça." + +#: ../../glossary.rst:1414 msgid "Zen of Python" msgstr "Zen do Python" -#: ../../glossary.rst:1313 +#: ../../glossary.rst:1416 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 +3498,26 @@ msgstr "" "compreensão e uso da linguagem. A lista é exibida quando se digita " "\"``import this``\" no console interativo." -#: ../../glossary.rst:256 +#: ../../glossary.rst:24 +msgid "..." +msgstr "..." + +#: ../../glossary.rst:24 +msgid "ellipsis literal" +msgstr "literal de reticências" + +#: ../../glossary.rst:294 msgid "C-contiguous" msgstr "contíguo C" -#: ../../glossary.rst:256 +#: ../../glossary.rst:294 msgid "Fortran contiguous" msgstr "contíguo Fortran" -#: ../../glossary.rst:773 +#: ../../glossary.rst:838 msgid "magic" msgstr "mágico" -#: ../../glossary.rst:1170 +#: ../../glossary.rst:1244 msgid "special" msgstr "especial" diff --git a/howto/a-conceptual-overview-of-asyncio.po b/howto/a-conceptual-overview-of-asyncio.po new file mode 100644 index 000000000..764237fae --- /dev/null +++ b/howto/a-conceptual-overview-of-asyncio.po @@ -0,0 +1,1259 @@ +# 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: +# python-doc bot, 2025 +# Jessica Patricio , 2025 +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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/a-conceptual-overview-of-asyncio.rst:5 +msgid "A Conceptual Overview of :mod:`!asyncio`" +msgstr "Uma visão geral conceitual de :mod:`!asyncio`" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:7 +msgid "" +"This :ref:`HOWTO ` article seeks to help you build a sturdy mental " +"model of how :mod:`asyncio` fundamentally works, helping you understand the " +"how and why behind the recommended patterns." +msgstr "" +"Este artigo :ref:`COMOFAZER ` tem como objetivo ajudá-lo a " +"construir um modelo mental sólido de como :mod:`asyncio` funciona " +"fundamentalmente, ajudando-lhe a compreender o como e o porquê por trás dos " +"padrões recomendados." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:11 +msgid "" +"You might be curious about some key :mod:`!asyncio` concepts. By the end of " +"this article, you'll be able to comfortably answer these questions:" +msgstr "" +"Você pode estar curioso sobre alguns conceitos-chave de :mod:`!asyncio`. Ao " +"final deste artigo, você será capaz de responder confortavelmente a estas " +"perguntas:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:14 +msgid "What's happening behind the scenes when an object is awaited?" +msgstr "O que acontece nos bastidores quando um objeto é aguardado?" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:15 +msgid "" +"How does :mod:`!asyncio` differentiate between a task which doesn't need CPU " +"time (such as a network request or file read) as opposed to a task that does " +"(such as computing n-factorial)?" +msgstr "" +"Como o :mod:`!asyncio` diferencia uma tarefa que não precisa de tempo de CPU " +"(como uma solicitação de rede ou leitura de arquivo) de uma tarefa que " +"precisa (como calcular n-fatorial)?" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:18 +msgid "" +"How to write an asynchronous variant of an operation, such as an async sleep " +"or database request." +msgstr "" +"Como escrever uma variante assíncrona de uma operação, como uma suspensão " +"assíncrona ou uma solicitação de banco de dados." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:23 +msgid "" +"The `guide `_ that inspired this HOWTO article, by Alexander Nordin." +msgstr "" +"O `guia `_ que inspirou este artigo COMOFAZER, por Alexander Nordin." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:25 +msgid "" +"This in-depth `YouTube tutorial series `_ on ``asyncio`` " +"created by Python core team member, Łukasz Langa." +msgstr "" +"Esta `série de tutoriais detalhados do YouTube `_ sobre " +"``asyncio`` foi criada pelo membro da equipe principal do Python, Łukasz " +"Langa." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:28 +msgid "" +"`500 Lines or Less: A Web Crawler With asyncio Coroutines `_ by A. Jesse Jiryu " +"Davis and Guido van Rossum." +msgstr "" +"`500 linhas ou menos: um rastreador da Web com corrotinas asyncio `_ (em " +"inglês) por A. Jesse Jiryu Davis e Guido van Rossum." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:34 +msgid "A conceptual overview part 1: the high-level" +msgstr "Uma visão geral conceitual parte 1: o alto nível" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:36 +msgid "" +"In part 1, we'll cover the main, high-level building blocks of :mod:`!" +"asyncio`: the event loop, coroutine functions, coroutine objects, tasks, and " +"``await``." +msgstr "" +"Na parte 1, abordaremos os principais blocos de construção de alto nível de :" +"mod:`!asyncio`: o laço de eventos, funções de corrotina, objetos de " +"corrotina, tarefas e ``await``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:41 +msgid "Event Loop" +msgstr "Laço de Eventos" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:43 +msgid "" +"Everything in :mod:`!asyncio` happens relative to the event loop. It's the " +"star of the show. It's like an orchestra conductor. It's behind the scenes " +"managing resources. Some power is explicitly granted to it, but a lot of its " +"ability to get things done comes from the respect and cooperation of its " +"worker bees." +msgstr "" +"Tudo em :mod:`!asyncio` acontece em relação ao laço de eventos. Ele é a " +"estrela do show. É como um maestro de orquestra. Está nos bastidores, " +"gerenciando recursos. Algum poder lhe é explicitamente concedido, mas grande " +"parte de sua capacidade de realizar tarefas advém do respeito e da " +"cooperação de seus operários." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:50 +msgid "" +"In more technical terms, the event loop contains a collection of jobs to be " +"run. Some jobs are added directly by you, and some indirectly by :mod:`!" +"asyncio`. The event loop takes a job from its backlog of work and invokes it " +"(or \"gives it control\"), similar to calling a function, and then that job " +"runs. Once it pauses or completes, it returns control to the event loop. The " +"event loop will then select another job from its pool and invoke it. You can " +"*roughly* think of the collection of jobs as a queue: jobs are added and " +"then processed one at a time, generally (but not always) in order. This " +"process repeats indefinitely, with the event loop cycling endlessly onwards. " +"If there are no more jobs pending execution, the event loop is smart enough " +"to rest and avoid needlessly wasting CPU cycles, and will come back when " +"there's more work to be done." +msgstr "" +"Em termos mais técnicos, o laço de eventos contém uma coleção de tarefas a " +"serem executadas. Algumas tarefas são adicionadas diretamente por você e " +"outras indiretamente por :mod:`!asyncio`. O laço de eventos pega uma tarefa " +"do seu backlog de tarefas e a invoca (ou \"dá a ela o controle\"), " +"semelhante a chamar uma função, e então essa tarefa é executada. Uma vez " +"pausada ou concluída, ela retorna o controle para o laço de eventos. O laço " +"de eventos então seleciona outra tarefa do seu pool e a invoca. Você pode " +"*aproximadamente* pensar na coleção de tarefas como uma fila: as tarefas são " +"adicionadas e processadas uma de cada vez, geralmente (mas nem sempre) em " +"ordem. Esse processo se repete indefinidamente, com o laço de eventos em " +"ciclos infinitos. Se não houver mais tarefas pendentes de execução, o laço " +"de eventos é inteligente o suficiente para descansar e evitar o desperdício " +"desnecessário de ciclos de CPU, e retornará quando houver mais trabalho a " +"ser feito." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:64 +msgid "" +"Effective execution relies on jobs sharing well and cooperating; a greedy " +"job could hog control and leave the other jobs to starve, rendering the " +"overall event loop approach rather useless." +msgstr "" +"A execução eficaz depende do bom compartilhamento e da cooperação entre as " +"tarefas; uma tarefa gananciosa pode monopolizar o controle e deixar as " +"outras tarefas na miséria, tornando a abordagem geral do laço de eventos " +"inútil." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:70 +msgid "" +"import asyncio\n" +"\n" +"# This creates an event loop and indefinitely cycles through\n" +"# its collection of jobs.\n" +"event_loop = asyncio.new_event_loop()\n" +"event_loop.run_forever()" +msgstr "" +"import asyncio\n" +"\n" +"# Isso cria um laço de eventos e percorre indefinidamente\n" +"# sua coleção de trabalhos\n" +"event_loop = asyncio.new_event_loop()\n" +"event_loop.run_forever()" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:79 +msgid "Asynchronous functions and coroutines" +msgstr "Funções assíncronas e corrotinas" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:81 +msgid "This is a basic, boring Python function::" +msgstr "Esta é uma função básica e chata do Python::" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:83 +msgid "" +"def hello_printer():\n" +" print(\n" +" \"Hi, I am a lowly, simple printer, though I have all I \"\n" +" \"need in life -- \\nfresh paper and my dearly beloved octopus \"\n" +" \"partner in crime.\"\n" +" )" +msgstr "" +"def hello_printer():\n" +" print(\n" +" \"Olá, sou uma impressora humilde e simples, embora tenha tudo \"\n" +" \"que preciso na vida: -- \\npapel novo e meu querido e amado \"\n" +" \"parceiro no crime, o polvo.\"\n" +" )" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:90 +msgid "Calling a regular function invokes its logic or body::" +msgstr "Chamar uma função regular invoca sua lógica ou corpo::" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:92 +msgid "" +">>> hello_printer()\n" +"Hi, I am a lowly, simple printer, though I have all I need in life --\n" +"fresh paper and my dearly beloved octopus partner in crime." +msgstr "" +">>> hello_printer()\n" +"Olá, sou uma impressora humilde e simples, embora tenha tudo o que preciso " +"na vida:\n" +"papel novo e meu querido e amado parceiro no crime, o polvo." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:96 +msgid "" +"The :ref:`async def `, as opposed to just a plain ``def``, makes " +"this an asynchronous function (or \"coroutine function\"). Calling it " +"creates and returns a :ref:`coroutine ` object." +msgstr "" +"O :ref:`async def `, em oposição a um simples ``def``, torna esta " +"uma função assíncrona (ou \"função de corrotina\"). Chamá-la cria e retorna " +"um objeto :ref:`corrotina `." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:102 +msgid "" +"async def loudmouth_penguin(magic_number: int):\n" +" print(\n" +" \"I am a super special talking penguin. Far cooler than that printer. " +"\"\n" +" f\"By the way, my lucky number is: {magic_number}.\"\n" +" )" +msgstr "" +"async def loudmouth_penguin(magic_number: int):\n" +" print(\n" +" \"Eu sou um pinguim falante superespecial. Muito mais legal que aquela " +"impressora. \"\n" +" f\"Aliás, meu número da sorte é: {magic_number}.\"\n" +" )" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:108 +msgid "" +"Calling the async function, ``loudmouth_penguin``, does not execute the " +"print statement; instead, it creates a coroutine object::" +msgstr "" +"Chamar a função assíncrona, ``loudmouth_penguin``, não executa a instrução " +"de impressão; em vez disso, cria um objeto corrotina::" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:111 +msgid "" +">>> loudmouth_penguin(magic_number=3)\n" +"" +msgstr "" +">>> loudmouth_penguin(magic_number=3)\n" +"" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:114 +msgid "" +"The terms \"coroutine function\" and \"coroutine object\" are often " +"conflated as coroutine. That can be confusing! In this article, coroutine " +"specifically refers to a coroutine object, or more precisely, an instance " +"of :data:`types.CoroutineType` (native coroutine). Note that coroutines can " +"also exist as instances of :class:`collections.abc.Coroutine` -- a " +"distinction that matters for type checking." +msgstr "" +"Os termos \"função de corrotina\" e \"objeto corrotina\" são frequentemente " +"confundidos com corrotina. Isso pode ser confuso! Neste artigo, corrotina se " +"refere especificamente a um objeto corrotina, ou mais precisamente, a uma " +"instância de :data:`types.CoroutineType` (corrotina nativa). Observe que " +"corrotinas também podem existir como instâncias de :class:`collections.abc." +"Coroutine` — uma distinção importante para a verificação de tipos." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:123 +msgid "" +"A coroutine represents the function's body or logic. A coroutine has to be " +"explicitly started; again, merely creating the coroutine does not start it. " +"Notably, the coroutine can be paused and resumed at various points within " +"the function's body. That pausing and resuming ability is what allows for " +"asynchronous behavior!" +msgstr "" +"Uma corrotina representa o corpo ou a lógica da função. Uma corrotina " +"precisa ser iniciada explicitamente; novamente, a mera criação da corrotina " +"não a inicia. Notavelmente, a corrotina pode ser pausada e retomada em " +"vários pontos do corpo da função. Essa capacidade de pausar e retomar é o " +"que permite o comportamento assíncrono!" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:130 +msgid "" +"Coroutines and coroutine functions were built by leveraging the " +"functionality of :term:`generators ` and :term:" +"`generator functions `. Recall, a generator function is a " +"function that :keyword:`yield`\\s, like this one::" +msgstr "" +"Corrotinas e funções de corrotina foram criadas aproveitando a " +"funcionalidade de :term:`geradores ` e :term:`funções " +"geradoras `. Lembre-se: uma função geradora é uma função que " +"executa :keyword:`yield`, como esta::" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:136 +msgid "" +"def get_random_number():\n" +" # This would be a bad random number generator!\n" +" print(\"Hi\")\n" +" yield 1\n" +" print(\"Hello\")\n" +" yield 7\n" +" print(\"Howdy\")\n" +" yield 4\n" +" ..." +msgstr "" +"def get_random_number():\n" +" # Este seria um gerador de número aleatório ruim!\n" +" print(\"Oi\")\n" +" yield 1\n" +" print(\"Olá\")\n" +" yield 7\n" +" print(\"E aí\")\n" +" yield 4\n" +" ..." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:146 +msgid "" +"Similar to a coroutine function, calling a generator function does not run " +"it. Instead, it creates a generator object::" +msgstr "" +"Semelhante a uma função de corrotina, chamar uma função geradora não a " +"executa. Em vez disso, ela cria um objeto gerador:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:149 +msgid "" +">>> get_random_number()\n" +"" +msgstr "" +">>> get_random_number()\n" +"" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:152 +msgid "" +"You can proceed to the next ``yield`` of a generator by using the built-in " +"function :func:`next`. In other words, the generator runs, then pauses. For " +"example::" +msgstr "" +"Você pode prosseguir para o próximo ``yield`` de um gerador usando a função " +"embutida :func:`next`. Em outras palavras, o gerador é executado e, em " +"seguida, pausado. Por exemplo:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:157 +msgid "" +">>> generator = get_random_number()\n" +">>> next(generator)\n" +"Hi\n" +"1\n" +">>> next(generator)\n" +"Hello\n" +"7" +msgstr "" +">>> generator = get_random_number()\n" +">>> next(generator)\n" +"Oi\n" +"1\n" +">>> next(generator)\n" +"Olá\n" +"7" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:167 +msgid "Tasks" +msgstr "Tarefas" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:169 +msgid "" +"Roughly speaking, :ref:`tasks ` are coroutines (not " +"coroutine functions) tied to an event loop. A task also maintains a list of " +"callback functions whose importance will become clear in a moment when we " +"discuss :keyword:`await`. The recommended way to create tasks is via :func:" +"`asyncio.create_task`." +msgstr "" +"Em termos gerais, :ref:`tarefas ` são corrotinas (não " +"funções de corrotina) vinculadas a um laço de eventos. Uma tarefa também " +"mantém uma lista de funções de retorno de chamada cuja importância ficará " +"clara em breve, quando discutirmos :keyword:`await`. A maneira recomendada " +"de criar tarefas é via :func:`asyncio.create_task`." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:175 +msgid "" +"Creating a task automatically schedules it for execution (by adding a " +"callback to run it in the event loop's to-do list, that is, collection of " +"jobs)." +msgstr "" +"A criação de uma tarefa a agenda automaticamente para execução (adicionando " +"um retorno de chamada para executá-la na lista de tarefas do laço de " +"eventos, ou seja, coleção de tarefas)." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:178 +msgid "" +"Since there's only one event loop (in each thread), :mod:`!asyncio` takes " +"care of associating the task with the event loop for you. As such, there's " +"no need to specify the event loop." +msgstr "" +"Como há apenas um laço de eventos (em cada thread), :mod:`!asyncio` se " +"encarrega de associar a tarefa ao laço de eventos para você. Portanto, não " +"há necessidade de especificar o laço de eventos." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:184 +msgid "" +"coroutine = loudmouth_penguin(magic_number=5)\n" +"# This creates a Task object and schedules its execution via the event " +"loop.\n" +"task = asyncio.create_task(coroutine)" +msgstr "" +"coroutine = loudmouth_penguin(magic_number=5)\n" +"# Isso cria um objeto Task e agenda sua execução por meio do laço de " +"eventos.\n" +"task = asyncio.create_task(coroutine)" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:188 +msgid "" +"Earlier, we manually created the event loop and set it to run forever. In " +"practice, it's recommended to use (and common to see) :func:`asyncio.run`, " +"which takes care of managing the event loop and ensuring the provided " +"coroutine finishes before advancing. For example, many async programs follow " +"this setup::" +msgstr "" +"Anteriormente, criamos manualmente o laço de eventos e o configuramos para " +"ser executado indefinidamente. Na prática, é recomendado (e comum) usar :" +"func:`asyncio.run`, que gerencia o laço de eventos e garante que a corrotina " +"fornecida termine antes de avançar. Por exemplo, muitos programas " +"assíncronos seguem esta configuração:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:194 +msgid "" +"import asyncio\n" +"\n" +"async def main():\n" +" # Perform all sorts of wacky, wild asynchronous things...\n" +" ...\n" +"\n" +"if __name__ == \"__main__\":\n" +" asyncio.run(main())\n" +" # The program will not reach the following print statement until the\n" +" # coroutine main() finishes.\n" +" print(\"coroutine main() is done!\")" +msgstr "" +"import asyncio\n" +"\n" +"async def main():\n" +" # Faz todo tipo de coisas malucas, selvagens e assíncronas...\n" +" ...\n" +"\n" +"if __name__ == \"__main__\":\n" +" asyncio.run(main())\n" +" # O programa não alcançará a seguinte instrução de exibição\n" +" # até que o main() da corrotina seja finalizado.\n" +" print(\"main() da corrotina concluiu!\")" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:206 +msgid "" +"It's important to be aware that the task itself is not added to the event " +"loop, only a callback to the task is. This matters if the task object you " +"created is garbage collected before it's called by the event loop. For " +"example, consider this program:" +msgstr "" +"É importante estar ciente de que a tarefa em si não é adicionada ao laço de " +"eventos, apenas um retorno de chamada para a tarefa. Isso é importante se o " +"objeto de tarefa que você criou for coletado como lixo antes de ser chamado " +"pelo laço de eventos. Por exemplo, considere este programa:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:212 +msgid "" +"async def hello():\n" +" print(\"hello!\")\n" +"\n" +"async def main():\n" +" asyncio.create_task(hello())\n" +" # Other asynchronous instructions which run for a while\n" +" # and cede control to the event loop...\n" +" ...\n" +"\n" +"asyncio.run(main())" +msgstr "" +"async def hello():\n" +" print(\"hello!\")\n" +"\n" +"async def main():\n" +" asyncio.create_task(hello())\n" +" # Outras instruções assíncronas que são executadas por\n" +" # um tempo e cedem o controle ao laço de eventos...\n" +" ...\n" +"\n" +"asyncio.run(main())" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:226 +msgid "" +"Because there's no reference to the task object created on line 5, it " +"*might* be garbage collected before the event loop invokes it. Later " +"instructions in the coroutine ``main()`` hand control back to the event loop " +"so it can invoke other jobs. When the event loop eventually tries to run the " +"task, it might fail and discover the task object does not exist! This can " +"also happen even if a coroutine keeps a reference to a task but completes " +"before that task finishes. When the coroutine exits, local variables go out " +"of scope and may be subject to garbage collection. In practice, ``asyncio`` " +"and Python's garbage collector work pretty hard to ensure this sort of thing " +"doesn't happen. But that's no reason to be reckless!" +msgstr "" +"Como não há referência ao objeto tarefa criado na linha 5, ele *pode* ser " +"coletado como lixo antes que o laço de eventos o invoque. Instruções " +"posteriores na corrotina ``main()`` transferem o controle de volta para o " +"laço de eventos para que ele possa invocar outras tarefas. Quando o laço de " +"eventos eventualmente tenta executar a tarefa, pode falhar e descobrir que o " +"objeto task não existe! Isso também pode acontecer mesmo que uma corrotina " +"mantenha uma referência a uma tarefa, mas seja concluída antes que ela " +"termine. Quando a corrotina termina, as variáveis locais saem do escopo e " +"podem estar sujeitas à coleta de lixo. Na prática, ``asyncio`` e o coletor " +"de lixo do Python trabalham arduamente para garantir que esse tipo de coisa " +"não aconteça. Mas isso não é motivo para ser imprudente!" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:242 +msgid "await" +msgstr "await" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:244 +msgid "" +":keyword:`await` is a Python keyword that's commonly used in one of two " +"different ways::" +msgstr "" +":keyword:`await` é uma palavra reservada do Python comumente usada de duas " +"maneiras diferentes::" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:247 +msgid "" +"await task\n" +"await coroutine" +msgstr "" +"await task\n" +"await coroutine" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:250 +msgid "" +"In a crucial way, the behavior of ``await`` depends on the type of object " +"being awaited." +msgstr "" +"De maneira crucial, o comportamento de ``await`` depende do tipo de objeto " +"que está sendo aguardado." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:253 +msgid "" +"Awaiting a task will cede control from the current task or coroutine to the " +"event loop. In the process of relinquishing control, a few important things " +"happen. We'll use the following code example to illustrate::" +msgstr "" +"Aguardar uma tarefa cederá o controle da tarefa ou corrotina atual para o " +"laço de eventos. No processo de cessão de controle, algumas coisas " +"importantes acontecem. Usaremos o seguinte exemplo de código para ilustrar:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:258 +msgid "" +"async def plant_a_tree():\n" +" dig_the_hole_task = asyncio.create_task(dig_the_hole())\n" +" await dig_the_hole_task\n" +"\n" +" # Other instructions associated with planting a tree.\n" +" ..." +msgstr "" +"async def plant_a_tree():\n" +" dig_the_hole_task = asyncio.create_task(dig_the_hole())\n" +" await dig_the_hole_task\n" +"\n" +" # Outras instruções associadas com plantar uma árvore.\n" +" ..." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:265 +msgid "" +"In this example, imagine the event loop has passed control to the start of " +"the coroutine ``plant_a_tree()``. As seen above, the coroutine creates a " +"task and then awaits it. The ``await dig_the_hole_task`` instruction adds a " +"callback (which will resume ``plant_a_tree()``) to the ``dig_the_hole_task`` " +"object's list of callbacks. And then, the instruction cedes control to the " +"event loop. Some time later, the event loop will pass control to " +"``dig_the_hole_task`` and the task will finish whatever it needs to do. Once " +"the task finishes, it will add its various callbacks to the event loop, in " +"this case, a call to resume ``plant_a_tree()``." +msgstr "" +"Neste exemplo, imagine que o laço de eventos passou o controle para o início " +"da corrotina ``plant_a_tree()``. Como visto acima, a corrotina cria uma " +"tarefa e a aguarda. A instrução ``await dig_the_hole_task`` adiciona um " +"retorno de chamada (que retomará ``plant_a_tree()``) à lista de retornos de " +"chamada do objeto ``dig_the_hole_task``. E então, a instrução cede o " +"controle para o laço de eventos. Algum tempo depois, o laço de eventos " +"passará o controle para ``dig_the_hole_task`` e a tarefa concluirá o que for " +"necessário. Assim que a tarefa for concluída, ela adicionará seus vários " +"retornos de chamada ao laço de eventos, neste caso, uma chamada para retomar " +"``plant_a_tree()``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:276 +msgid "" +"Generally speaking, when the awaited task finishes (``dig_the_hole_task``), " +"the original task or coroutine (``plant_a_tree()``) is added back to the " +"event loop's to-do list to be resumed." +msgstr "" +"De modo geral, quando a tarefa aguardada termina (``dig_the_hole_task``), a " +"tarefa original ou corrotina (``plant_a_tree()``) é adicionada novamente à " +"lista de tarefas do laço de eventos para ser retomada." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:280 +msgid "" +"This is a basic, yet reliable mental model. In practice, the control " +"handoffs are slightly more complex, but not by much. In part 2, we'll walk " +"through the details that make this possible." +msgstr "" +"Este é um modelo mental básico, porém confiável. Na prática, as " +"transferências de controle são um pouco mais complexas, mas não muito. Na " +"parte 2, abordaremos os detalhes que tornam isso possível." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:284 +msgid "" +"**Unlike tasks, awaiting a coroutine does not hand control back to the event " +"loop!** Wrapping a coroutine in a task first, then awaiting that would cede " +"control. The behavior of ``await coroutine`` is effectively the same as " +"invoking a regular, synchronous Python function. Consider this program::" +msgstr "" +"**Ao contrário de tarefas, aguardar uma corrotina não devolve o controle ao " +"laço de eventos!** Envolver uma corrotina em uma tarefa primeiro e depois " +"aguardar isso cederia o controle. O comportamento de ``await coroutine`` é " +"efetivamente o mesmo que invocar uma função Python síncrona comum. Considere " +"este programa:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:292 +msgid "" +"import asyncio\n" +"\n" +"async def coro_a():\n" +" print(\"I am coro_a(). Hi!\")\n" +"\n" +"async def coro_b():\n" +" print(\"I am coro_b(). I sure hope no one hogs the event loop...\")\n" +"\n" +"async def main():\n" +" task_b = asyncio.create_task(coro_b())\n" +" num_repeats = 3\n" +" for _ in range(num_repeats):\n" +" await coro_a()\n" +" await task_b\n" +"\n" +"asyncio.run(main())" +msgstr "" +"import asyncio\n" +"\n" +"async def coro_a():\n" +" print(\"Sou coro_a(). Oi!\")\n" +"\n" +"async def coro_b():\n" +" print(\"Sou coro_b(). Espero que ninguém monopolize o laço de eventos..." +"\")\n" +"\n" +"async def main():\n" +" task_b = asyncio.create_task(coro_b())\n" +" num_repeats = 3\n" +" for _ in range(num_repeats):\n" +" await coro_a()\n" +" await task_b\n" +"\n" +"asyncio.run(main())" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:309 +msgid "" +"The first statement in the coroutine ``main()`` creates ``task_b`` and " +"schedules it for execution via the event loop. Then, ``coro_a()`` is " +"repeatedly awaited. Control never cedes to the event loop, which is why we " +"see the output of all three ``coro_a()`` invocations before ``coro_b()``'s " +"output:" +msgstr "" +"A primeira instrução na corrotina ``main()`` cria ``task_b`` e a agenda para " +"execução via laço de eventos. Em seguida, ``coro_a()`` é aguardado " +"repetidamente. O controle nunca cede ao laço de eventos, e é por isso que " +"vemos a saída de todas as três invocações de ``coro_a()`` antes da saída de " +"``coro_b()``:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:315 +msgid "" +"I am coro_a(). Hi!\n" +"I am coro_a(). Hi!\n" +"I am coro_a(). Hi!\n" +"I am coro_b(). I sure hope no one hogs the event loop..." +msgstr "" +"Sou coro_a(). Oi!\n" +"Sou coro_a(). Oi!\n" +"Sou coro_a(). Oi!\n" +"Sou coro_b(). Espero que ninguém monopolize o laço de eventos..." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:322 +msgid "" +"If we change ``await coro_a()`` to ``await asyncio.create_task(coro_a())``, " +"the behavior changes. The coroutine ``main()`` cedes control to the event " +"loop with that statement. The event loop then proceeds through its backlog " +"of work, calling ``task_b`` and then the task which wraps ``coro_a()`` " +"before resuming the coroutine ``main()``." +msgstr "" +"Se alterarmos ``await coro_a()`` para ``await asyncio." +"create_task(coro_a())``, o comportamento muda. A corrotina ``main()`` cede o " +"controle ao laço de eventos com essa instrução. O laço de eventos então " +"prossegue com seu backlog de trabalho, chamando ``task_b`` e, em seguida, a " +"tarefa que encerra ``coro_a()`` antes de retomar a corrotina ``main()``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:329 +msgid "" +"I am coro_b(). I sure hope no one hogs the event loop...\n" +"I am coro_a(). Hi!\n" +"I am coro_a(). Hi!\n" +"I am coro_a(). Hi!" +msgstr "" +"Sou coro_b(). Espero que ninguém monopolize o laço de eventos...\n" +"Sou coro_a(). Oi!\n" +"Sou coro_a(). Oi!\n" +"Sou coro_a(). Oi!" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:336 +msgid "" +"This behavior of ``await coroutine`` can trip a lot of people up! That " +"example highlights how using only ``await coroutine`` could unintentionally " +"hog control from other tasks and effectively stall the event loop. :func:" +"`asyncio.run` can help you detect such occurrences via the ``debug=True`` " +"flag, which enables :ref:`debug mode `. Among other " +"things, it will log any coroutines that monopolize execution for 100ms or " +"longer." +msgstr "" +"Esse comportamento de ``await coroutine`` pode confundir muita gente! Este " +"exemplo destaca como usar apenas ``await coroutine`` pode, " +"involuntariamente, monopolizar o controle de outras tarefas e efetivamente " +"paralisar o laço de eventos. :func:`asyncio.run` pode ajudar a detectar tais " +"ocorrências por meio do sinalizador ``debug=True``, que habilita o :ref:" +"`modo de depuração `. Entre outras coisas, ele " +"registrará quaisquer corrotinas que monopolizem a execução por 100 ms ou " +"mais." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:346 +msgid "" +"The design intentionally trades off some conceptual clarity around usage of " +"``await`` for improved performance. Each time a task is awaited, control " +"needs to be passed all the way up the call stack to the event loop. That " +"might sound minor, but in a large program with many ``await`` statements and " +"a deep call stack, that overhead can add up to a meaningful performance drag." +msgstr "" +"O design intencionalmente troca alguma clareza conceitual em torno do uso de " +"``await`` por melhor desempenho. Cada vez que uma tarefa é aguardada, o " +"controle precisa ser passado por toda a pilha de chamadas até o laço de " +"eventos. Isso pode parecer insignificante, mas em um programa grande com " +"muitas instruções ``await`` e uma pilha de chamadas extensa, essa sobrecarga " +"pode representar um significativo prejuízo ao desempenho." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:355 +msgid "A conceptual overview part 2: the nuts and bolts" +msgstr "Uma visão geral conceitual, parte 2: os detalhes" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:357 +msgid "" +"Part 2 goes into detail on the mechanisms :mod:`!asyncio` uses to manage " +"control flow. This is where the magic happens. You'll come away from this " +"section knowing what ``await`` does behind the scenes and how to make your " +"own asynchronous operators." +msgstr "" +"A parte 2 detalha os mecanismos que :mod:`!asyncio` usa para gerenciar o " +"fluxo de controle. É aqui que a mágica acontece. Você sairá desta seção " +"sabendo o que ``await`` faz nos bastidores e como criar seus próprios " +"operadores assíncronos." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:365 +msgid "The inner workings of coroutines" +msgstr "O funcionamento interno das corrotinas" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:367 +msgid ":mod:`!asyncio` leverages four components to pass around control." +msgstr ":mod:`!asyncio` utiliza quatro componentes para passar o controle." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:369 +msgid "" +":meth:`coroutine.send(arg) ` is the method used to start or " +"resume a coroutine. If the coroutine was paused and is now being resumed, " +"the argument ``arg`` will be sent in as the return value of the ``yield`` " +"statement which originally paused it. If the coroutine is being used for the " +"first time (as opposed to being resumed), ``arg`` must be ``None``." +msgstr "" +":meth:`coroutine.send(arg) ` é o método usado para iniciar " +"ou retomar uma corrotina. Se a corrotina foi pausada e agora está sendo " +"retomada, o argumento ``arg`` será enviado como valor de retorno da " +"instrução ``yield`` que a pausou originalmente. Se a corrotina estiver sendo " +"usada pela primeira vez (em vez de ser retomada), ``arg`` deve ser ``None``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:377 +msgid "" +"class Rock:\n" +" def __await__(self):\n" +" value_sent_in = yield 7\n" +" print(f\"Rock.__await__ resuming with value: {value_sent_in}.\")\n" +" return value_sent_in\n" +"\n" +"async def main():\n" +" print(\"Beginning coroutine main().\")\n" +" rock = Rock()\n" +" print(\"Awaiting rock...\")\n" +" value_from_rock = await rock\n" +" print(f\"Coroutine received value: {value_from_rock} from rock.\")\n" +" return 23\n" +"\n" +"coroutine = main()\n" +"intermediate_result = coroutine.send(None)\n" +"print(f\"Coroutine paused and returned intermediate value: " +"{intermediate_result}.\")\n" +"\n" +"print(f\"Resuming coroutine and sending in value: 42.\")\n" +"try:\n" +" coroutine.send(42)\n" +"except StopIteration as e:\n" +" returned_value = e.value\n" +"print(f\"Coroutine main() finished and provided value: {returned_value}.\")" +msgstr "" +"class Rock:\n" +" def __await__(self):\n" +" value_sent_in = yield 7\n" +" print(f\"Rock.__await__ resumindo com o valor: {value_sent_in}.\")\n" +" return value_sent_in\n" +"\n" +"async def main():\n" +" print(\"Iniciando main() da corrotina.\")\n" +" rock = Rock()\n" +" print(\"Aguardando rock...\")\n" +" value_from_rock = await rock\n" +" print(f\"Corrotina recebeu valor: {value_from_rock} de rock.\")\n" +" return 23\n" +"\n" +"coroutine = main()\n" +"intermediate_result = coroutine.send(None)\n" +"print(f\"Corrotina pausou e retornou o valor intermediário: " +"{intermediate_result}.\")\n" +"\n" +"print(f\"Resumindo corrotina e enviando o valor: 42.\")\n" +"try:\n" +" coroutine.send(42)\n" +"except StopIteration as e:\n" +" returned_value = e.value\n" +"print(f\"O main() da corrotina finalizou e forneceu o valor: " +"{returned_value}.\")" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:405 +msgid "" +":ref:`yield `, as usual, pauses execution and returns control to " +"the caller. In the example above, the ``yield``, on line 3, is called by " +"``... = await rock`` on line 11. More broadly speaking, ``await`` calls the :" +"meth:`~object.__await__` method of the given object. ``await`` also does one " +"more very special thing: it propagates (or \"passes along\") any ``yield``\\ " +"s it receives up the call chain. In this case, that's back to ``... = " +"coroutine.send(None)`` on line 16." +msgstr "" +":ref:`yield `, como de costume, pausa a execução e retorna o " +"controle ao chamador. No exemplo acima, ``yield``, na linha 3, é chamado por " +"``... = await rock`` na linha 11. Em termos mais gerais, ``await`` chama o " +"método :meth:`~object.__await__` do objeto fornecido. ``await`` também faz " +"algo muito especial: ele propaga (ou \"repassa\") quaisquer ``yield``\\ s " +"que recebe na cadeia de chamadas. Neste caso, voltamos a ``... = coroutine." +"send(None)`` na linha 16." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:415 +msgid "" +"The coroutine is resumed via the ``coroutine.send(42)`` call on line 21. The " +"coroutine picks back up from where it ``yield``\\ ed (or paused) on line 3 " +"and executes the remaining statements in its body. When a coroutine " +"finishes, it raises a :exc:`StopIteration` exception with the return value " +"attached in the :attr:`~StopIteration.value` attribute." +msgstr "" +"A corrotina é retomada por meio da chamada ``coroutine.send(42)`` na linha " +"21. A corrotina continua de onde foi executada (ou pausada) com ``yield`` na " +"linha 3 e executa as instruções restantes em seu corpo. Quando uma corrotina " +"termina, ela levanta uma exceção :exc:`StopIteration` com o valor de retorno " +"anexado ao atributo :attr:`~StopIteration.value`." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:421 +msgid "That snippet produces this output:" +msgstr "Esse trecho de código produz esta saída:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:423 +msgid "" +"Beginning coroutine main().\n" +"Awaiting rock...\n" +"Coroutine paused and returned intermediate value: 7.\n" +"Resuming coroutine and sending in value: 42.\n" +"Rock.__await__ resuming with value: 42.\n" +"Coroutine received value: 42 from rock.\n" +"Coroutine main() finished and provided value: 23." +msgstr "" +"Iniciando main() da corrotina.\n" +"Aguardando rock...\n" +"Corrotina pausou e retornou o valor intermediário: 7.\n" +"Resumindo coroutine e enviando o valor: 42.\n" +"Rock.__await__ resumindo com o valor: 42.\n" +"Corrotina recebeu valor: 42 de rock.\n" +"O main() da corrotina finalizou e forneceu o valor: 23." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:433 +msgid "" +"It's worth pausing for a moment here and making sure you followed the " +"various ways that control flow and values were passed. A lot of important " +"ideas were covered and it's worth ensuring your understanding is firm." +msgstr "" +"Vale a pena parar um momento aqui e certificar-se de que você seguiu as " +"diversas maneiras pelas quais o fluxo de controle e os valores foram " +"passados. Muitas ideias importantes foram abordadas e vale a pena garantir " +"que seu entendimento esteja firme." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:437 +msgid "" +"The only way to yield (or effectively cede control) from a coroutine is to " +"``await`` an object that ``yield``\\ s in its ``__await__`` method. That " +"might sound odd to you. You might be thinking:" +msgstr "" +"A única maneira de ceder (ou efetivamente ceder o controle) de uma corrotina " +"é ``await`` um objeto que ``yield`` está em seu método ``__await__``. Isso " +"pode parecer estranho para você. Você pode estar pensando:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:441 +msgid "" +"1. What about a ``yield`` directly within the coroutine function? The " +"coroutine function becomes an :ref:`async generator function `, a different beast entirely." +msgstr "" +"1. Que tal um ``yield`` diretamente dentro da função de corrotina? A função " +"de corrotina se torna uma :ref:`função geradora assíncrona `, algo completamente diferente." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:446 +msgid "" +"2. What about a :ref:`yield from ` within the coroutine function " +"to a (plain) generator? That causes the error: ``SyntaxError: yield from not " +"allowed in a coroutine.`` This was intentionally designed for the sake of " +"simplicity -- mandating only one way of using coroutines. Initially " +"``yield`` was barred as well, but was re-accepted to allow for async " +"generators. Despite that, ``yield from`` and ``await`` effectively do the " +"same thing." +msgstr "" +"2. E quanto a um :ref:`yield from ` dentro da função de corrotina " +"para um gerador (simples)? Isso causa o erro: ``SyntaxError: yield from not " +"allowed in a coroutine.``. Isso foi intencionalmente projetado por uma " +"questão de simplicidade — exigindo apenas uma maneira de usar corrotinas. " +"Inicialmente, ``yield`` também foi proibido, mas foi reativado para permitir " +"geradores assíncronos. Apesar disso, ``yield from`` e ``await`` efetivamente " +"fazem a mesma coisa." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:457 +msgid "Futures" +msgstr "Futuros" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:459 +msgid "" +"A :ref:`future ` is an object meant to represent a " +"computation's status and result. The term is a nod to the idea of something " +"still to come or not yet happened, and the object is a way to keep an eye on " +"that something." +msgstr "" +"Um :ref:`future ` é um objeto que representa o status e " +"o resultado de uma computação. O termo é uma referência à ideia de algo que " +"ainda está por vir ou que ainda não aconteceu, e o objeto é uma forma de " +"ficar de olho nesse algo." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:464 +msgid "" +"A future has a few important attributes. One is its state, which can be " +"either \"pending\", \"cancelled\", or \"done\". Another is its result, which " +"is set when the state transitions to done. Unlike a coroutine, a future does " +"not represent the actual computation to be done; instead, it represents the " +"status and result of that computation, kind of like a status light (red, " +"yellow, or green) or indicator." +msgstr "" +"Um future possui alguns atributos importantes. Um deles é o seu estado, que " +"pode ser \"pending\", \"cancelled\", or \"done\" (\"pendente\", " +"\"cancelado\" ou \"concluído\", respectivamente). Outro é o seu resultado, " +"que é definido quando o estado transita para concluído. Ao contrário de uma " +"corrotina, um future não representa a computação real a ser realizada; em " +"vez disso, representa o status e o resultado dessa computação, como uma " +"espécie de luz de status (vermelha, amarela ou verde) ou indicador." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:471 +msgid "" +":class:`asyncio.Task` subclasses :class:`asyncio.Future` in order to gain " +"these various capabilities. The prior section said tasks store a list of " +"callbacks, which wasn't entirely accurate. It's actually the ``Future`` " +"class that implements this logic, which ``Task`` inherits." +msgstr "" +":class:`asyncio.Task` estende :class:`asyncio.Future` para obter esses " +"vários recursos. A seção anterior dizia que as tarefas armazenam uma lista " +"de retornos de chamada, o que não era totalmente preciso. Na verdade, é a " +"classe ``Future`` que implementa essa lógica, que ``Task`` herda." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:478 +msgid "" +"Futures may also be used directly (not via tasks). Tasks mark themselves as " +"done when their coroutine is complete. Futures are much more versatile and " +"will be marked as done when you say so. In this way, they're the flexible " +"interface for you to make your own conditions for waiting and resuming." +msgstr "" +"Instruções future também podem ser usados diretamente (não por meio de " +"tarefas). As tarefas se marcam como concluídas quando sua corrotina é " +"concluída. Instruções future são muito mais versáteis e serão marcados como " +"concluídos quando você informar. Dessa forma, eles são a interface flexível " +"para você definir suas próprias condições de espera e retomada." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:486 +msgid "A homemade asyncio.sleep" +msgstr "Um asyncio.sleep caseiro" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:488 +msgid "" +"We'll go through an example of how you could leverage a future to create " +"your own variant of asynchronous sleep (``async_sleep``) which mimics :func:" +"`asyncio.sleep`." +msgstr "" +"Veremos um exemplo de como você pode aproveitar um future para criar sua " +"própria variante de suspensão assíncrona (``async_sleep``) que imita :func:" +"`asyncio.sleep`." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:492 +msgid "" +"This snippet registers a few tasks with the event loop and then awaits the " +"task created by ``asyncio.create_task``, which wraps the ``async_sleep(3)`` " +"coroutine. We want that task to finish only after three seconds have " +"elapsed, but without preventing other tasks from running." +msgstr "" +"Este trecho de código registra algumas tarefas no laço de eventos e, em " +"seguida, aguarda a tarefa criada por ``asyncio.create_task``, que envolve a " +"corrotina ``async_sleep(3)``. Queremos que essa tarefa termine somente após " +"três segundos, mas sem impedir a execução de outras tarefas." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:499 +msgid "" +"async def other_work():\n" +" print(\"I like work. Work work.\")\n" +"\n" +"async def main():\n" +" # Add a few other tasks to the event loop, so there's something\n" +" # to do while asynchronously sleeping.\n" +" work_tasks = [\n" +" asyncio.create_task(other_work()),\n" +" asyncio.create_task(other_work()),\n" +" asyncio.create_task(other_work())\n" +" ]\n" +" print(\n" +" \"Beginning asynchronous sleep at time: \"\n" +" f\"{datetime.datetime.now().strftime(\"%H:%M:%S\")}.\"\n" +" )\n" +" await asyncio.create_task(async_sleep(3))\n" +" print(\n" +" \"Done asynchronous sleep at time: \"\n" +" f\"{datetime.datetime.now().strftime(\"%H:%M:%S\")}.\"\n" +" )\n" +" # asyncio.gather effectively awaits each task in the collection.\n" +" await asyncio.gather(*work_tasks)" +msgstr "" +"async def other_work():\n" +" print(\"Eu gosto de trabalhar. Trabalhar, trabalhar.\")\n" +"\n" +"async def main():\n" +" # Adiciona algumas tarefas ao laço de eventos, de forma que\n" +" # haja algo para fazer durante a suspensão assíncrona.\n" +" work_tasks = [\n" +" asyncio.create_task(other_work()),\n" +" asyncio.create_task(other_work()),\n" +" asyncio.create_task(other_work())\n" +" ]\n" +" print(\n" +" \"Começando a suspensão assíncrona no horário: \"\n" +" f\"{datetime.datetime.now().strftime(\"%H:%M:%S\")}.\"\n" +" )\n" +" await asyncio.create_task(async_sleep(3))\n" +" print(\n" +" \"Concluí a suspensão assíncrona no horário: \"\n" +" f\"{datetime.datetime.now().strftime(\"%H:%M:%S\")}.\"\n" +" )\n" +" # asyncio.gather efetivamente espera cada tarefa na coleção.\n" +" await asyncio.gather(*work_tasks)" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:523 +msgid "" +"Below, we use a future to enable custom control over when that task will be " +"marked as done. If :meth:`future.set_result() ` " +"(the method responsible for marking that future as done) is never called, " +"then this task will never finish. We've also enlisted the help of another " +"task, which we'll see in a moment, that will monitor how much time has " +"elapsed and, accordingly, call ``future.set_result()``." +msgstr "" +"A seguir, usamos um future para permitir o controle personalizado sobre " +"quando essa tarefa será marcada como concluída. Se :meth:`future." +"set_result() ` (o método responsável por marcar o " +"future como concluído) nunca for chamado, essa tarefa nunca terminará. " +"Também contamos com a ajuda de outra tarefa, que veremos em breve, que " +"monitorará o tempo decorrido e, consequentemente, chamará ``future." +"set_result()``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:534 +msgid "" +"async def async_sleep(seconds: float):\n" +" future = asyncio.Future()\n" +" time_to_wake = time.time() + seconds\n" +" # Add the watcher-task to the event loop.\n" +" watcher_task = asyncio.create_task(_sleep_watcher(future, " +"time_to_wake))\n" +" # Block until the future is marked as done.\n" +" await future" +msgstr "" +"async def async_sleep(seconds: float):\n" +" future = asyncio.Future()\n" +" time_to_wake = time.time() + seconds\n" +" # Adiciona uma tarefa de monitoramento ao laço de eventos.\n" +" watcher_task = asyncio.create_task(_sleep_watcher(future, " +"time_to_wake))\n" +" # Bloqueia até future ser marcado como concluído.\n" +" await future" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:542 +msgid "" +"Below, we use a rather bare ``YieldToEventLoop()`` object to ``yield`` from " +"its ``__await__`` method, ceding control to the event loop. This is " +"effectively the same as calling ``asyncio.sleep(0)``, but this approach " +"offers more clarity, not to mention it's somewhat cheating to use ``asyncio." +"sleep`` when showcasing how to implement it!" +msgstr "" +"A seguir, usamos um objeto ``YieldToEventLoop()`` bastante simples para " +"``yield`` do seu método ``__await__``, cedendo o controle ao laço de " +"eventos. Isso é efetivamente o mesmo que chamar ``asyncio.sleep(0)``, mas " +"essa abordagem oferece mais clareza, sem mencionar que é um tanto quanto " +"trapaça usar ``asyncio.sleep`` ao demonstrar como implementá-lo!" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:548 +msgid "" +"As usual, the event loop cycles through its tasks, giving them control and " +"receiving control back when they pause or finish. The ``watcher_task``, " +"which runs the coroutine ``_sleep_watcher(...)``, will be invoked once per " +"full cycle of the event loop. On each resumption, it'll check the time and " +"if not enough has elapsed, then it'll pause once again and hand control back " +"to the event loop. Once enough time has elapsed, ``_sleep_watcher(...)`` " +"marks the future as done and completes by exiting its infinite ``while`` " +"loop. Given this helper task is only invoked once per cycle of the event " +"loop, you'd be correct to note that this asynchronous sleep will sleep *at " +"least* three seconds, rather than exactly three seconds. Note this is also " +"true of ``asyncio.sleep``." +msgstr "" +"Como de costume, o laço de eventos percorre suas tarefas, concedendo-lhes o " +"controle e recebendo-o de volta quando elas pausam ou terminam. A tarefa " +"``watcher_task``, que executa a corrotina ``_sleep_watcher(...)``, será " +"invocada uma vez por ciclo completo do laço de eventos. A cada retomada, ela " +"verificará o tempo e, se não tiver decorrido tempo suficiente, pausará " +"novamente e devolverá o controle ao laço de eventos. Assim que o tempo " +"suficiente tiver decorrido, ``_sleep_watcher(...)`` marcará o futuro como " +"concluído e finalizará, saindo de seu laço ``while`` infinito. Dado que essa " +"tarefa auxiliar é invocada apenas uma vez por ciclo do laço de eventos, você " +"está correto ao observar que essa suspensão assíncrona durará *pelo menos* " +"três segundos, em vez de exatamente três segundos. Observe que isso também " +"se aplica a ``asyncio.sleep``." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:564 +msgid "" +"class YieldToEventLoop:\n" +" def __await__(self):\n" +" yield\n" +"\n" +"async def _sleep_watcher(future, time_to_wake):\n" +" while True:\n" +" if time.time() >= time_to_wake:\n" +" # This marks the future as done.\n" +" future.set_result(None)\n" +" break\n" +" else:\n" +" await YieldToEventLoop()" +msgstr "" +"class YieldToEventLoop:\n" +" def __await__(self):\n" +" yield\n" +"\n" +"async def _sleep_watcher(future, time_to_wake):\n" +" while True:\n" +" if time.time() >= time_to_wake:\n" +" # Isso marca future como concluído.\n" +" future.set_result(None)\n" +" break\n" +" else:\n" +" await YieldToEventLoop()" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:577 +msgid "Here is the full program's output:" +msgstr "Aqui está a saída completa do programa:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:579 +msgid "" +"$ python custom-async-sleep.py\n" +"Beginning asynchronous sleep at time: 14:52:22.\n" +"I like work. Work work.\n" +"I like work. Work work.\n" +"I like work. Work work.\n" +"Done asynchronous sleep at time: 14:52:25." +msgstr "" +"$ python custom-async-sleep.py\n" +"Começando a suspensão assíncrona no horário: 14:52:22.\n" +"Eu gosto de trabalhar. Trabalhar, trabalhar.\n" +"Eu gosto de trabalhar. Trabalhar, trabalhar.\n" +"Eu gosto de trabalhar. Trabalhar, trabalhar.\n" +"Concluí a suspensão assíncrona no horário: 14:52:25." + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:588 +msgid "" +"You might feel this implementation of asynchronous sleep was unnecessarily " +"convoluted. And, well, it was. The example was meant to showcase the " +"versatility of futures with a simple example that could be mimicked for more " +"complex needs. For reference, you could implement it without futures, like " +"so::" +msgstr "" +"Você pode achar que esta implementação de suspensão assíncrona foi " +"desnecessariamente complexa. E, bem, foi mesmo. O exemplo tinha como " +"objetivo demonstrar a versatilidade dos futures com um exemplo simples que " +"poderia ser replicado para necessidades mais complexas. Para referência, " +"você poderia implementá-lo sem futures, assim:" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:595 +msgid "" +"async def simpler_async_sleep(seconds):\n" +" time_to_wake = time.time() + seconds\n" +" while True:\n" +" if time.time() >= time_to_wake:\n" +" return\n" +" else:\n" +" await YieldToEventLoop()" +msgstr "" +"async def simpler_async_sleep(seconds):\n" +" time_to_wake = time.time() + seconds\n" +" while True:\n" +" if time.time() >= time_to_wake:\n" +" return\n" +" else:\n" +" await YieldToEventLoop()" + +#: ../../howto/a-conceptual-overview-of-asyncio.rst:603 +msgid "" +"But that's all for now. Hopefully you're ready to more confidently dive into " +"some async programming or check out advanced topics in the :mod:`rest of the " +"documentation `." +msgstr "" +"Mas por agora é tudo. Espero que agora esteja pronto para mergulhar com mais " +"confiança na programação assíncrona ou consultar tópicos avançados no :mod:" +"`restante da documentação `." diff --git a/howto/annotations.po b/howto/annotations.po index ba392c455..8a1c8bd9b 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..b36e5908b --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..fb6f43673 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..1edbda241 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..3978cc031 100644 --- a/howto/cporting.po +++ b/howto/cporting.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,12 +56,12 @@ msgstr "" #: ../../howto/cporting.rst:17 msgid "" -"The `Cython`_ and `CFFI`_ libraries offer abstractions over Python's C API. " -"Extensions generally need to be re-written to use one of them, but the " -"library then handles differences between various Python versions and " -"implementations." +":ref:`Recommended third party tools ` offer abstractions over " +"the Python's C API. Extensions generally need to be re-written to use one of " +"them, but the library then handles differences between various Python " +"versions and implementations." msgstr "" -"As bibliotecas `Cython`_ e `CFFI`_ oferecem abstrações sobre a API C do " -"Python. As extensões geralmente precisam ser reescritas para usar uma delas, " -"mas a biblioteca lida com diferenças entre várias versões e implementações " -"do Python." +":ref:`Ferramentas recomendadas de terceiros ` oferecem " +"abstrações sobre a API C do Python. As extensões geralmente precisam ser " +"reescritas para usar uma delas, mas a biblioteca lida com diferenças entre " +"várias versões e implementações do Python." diff --git a/howto/curses.po b/howto/curses.po index d38411bc3..c139a8e07 100644 --- a/howto/curses.po +++ b/howto/curses.po @@ -1,31 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,7 +54,7 @@ msgid "" "control text-mode displays." msgstr "" "Este documento descreve como usar o módulo de extensão :mod:`curses` para " -"controlar visualização em modo texto." +"controlar visualizações em modo texto." #: ../../howto/curses.rst:20 msgid "What is curses?" @@ -76,12 +71,12 @@ msgid "" "own minor quirks." msgstr "" "A biblioteca curses fornece formas que facilitam a impressão no terminal e o " -"tratamento de entrada do teclado para interfaces baseados em texto; tais " -"como interfaces produzidas para terminais incluindo VT100s, o console Linux, " -"e terminais fornecidos por vários programas. Terminais visuais suportam " -"vários códigos de controle para executar várias operações comuns como mover " -"o cursor, apagar áreas e rolagem de tela. Diferentes terminais usam uma gama " -"de diferentes códigos, e frequentemente têm suas próprias peculiaridades." +"tratamento de entrada via teclado para interfaces de terminal baseadas em " +"texto, tais como VT100s, o console Linux, e emuladores de terminais " +"fornecidos por vários programas. Terminais visuais suportam vários códigos " +"de controle para executar várias operações comuns como mover o cursor, " +"apagar áreas e rolagem de tela. Diferentes terminais usam uma gama de " +"diferentes códigos, e frequentemente têm suas próprias peculiaridades." #: ../../howto/curses.rst:30 msgid "" @@ -95,11 +90,11 @@ msgstr "" "No mundo dos displays gráficos, uma pergunta pode vir à tona \"por que isso, " "jovem?\". É verdade que os terminais de exibição de caracteres são uma " "tecnologia obsoleta, mas há nichos nos quais a capacidade de fazer coisas " -"sofisticadas com eles continua sendo valorizada. Um nicho são os programas " -"de small-footprint ou os Unixes embarcados, os quais não rodas um servidor " -"X, ou seja, não possuem interface gráfica. Outro nicho são o de ferramentas " -"como instaladores de sistemas operacionais e configurações de kernels que " -"devem rodar antes que qualquer suporte para interfaces gráficas esteja " +"sofisticadas com eles continua sendo valorizada. Um nicho são os Unixes de " +"baixa pegada de recursos ou embarcados, que não rodam um servidor X, ou " +"seja, não possuem interface gráfica. Outro nicho é o de ferramentas como " +"instaladores de sistemas operacionais e configurações de kernels que podem " +"precisar rodar antes que qualquer suporte a interfaces gráficas esteja " "disponível." #: ../../howto/curses.rst:38 @@ -113,6 +108,15 @@ msgid "" "interface concepts such as buttons, checkboxes, or dialogs; if you need such " "features, consider a user interface library such as :pypi:`Urwid`." msgstr "" +"A biblioteca curses fornece funcionalidades bastante básicas, proporcionando " +"ao programador uma abstração de um monitor contendo janelas de texto não " +"sobrepostas. Os conteúdos de uma janela podem ser modificados de diversas " +"formas---adicionando texto, apagando-o, modificando sua aparência---e a " +"biblioteca curses irá descobrir quais códigos de controle precisam ser " +"enviados ao terminal para produzir a saída correta. A biblioteca curses não " +"fornece muitos conceitos de interface de usuário como botões, caixas de " +"seleção ou diálogos; se você precisar desses recursos, considere uma " +"biblioteca de interface de usuário como :pypi:`Urwid`." #: ../../howto/curses.rst:48 msgid "" @@ -126,22 +130,24 @@ msgid "" "older versions of curses carried by some proprietary Unixes may not support " "everything, though." msgstr "" -"A biblioteca curses foi originalmente escrita para BSD Unix; as versões mais " -"recentes do System V do Unix da AT&T adicionaram muitos aprimoramentos e " -"novas funções. BSD curses não é mais mantida, tendo sido substituída por " -"ncursess, que é uma implementação de código aberto da interface da AT&T. Se " -"você estiver usando um sistema operacional de código aberto baseado em Unix, " -"tal como Linux ou FreeBSD, seu sistema provavelmente usa ncurses. Uma vez " -"que a maioria das versões comerciais do Unix são baseadas no código do " -"sistema V, todas as funções descritas aqui provavelmente estarão " +"A biblioteca curses foi originalmente escrita para o BSD Unix; as versões " +"mais recentes do System V do Unix da AT&T adicionaram muitos aprimoramentos " +"e novas funções. A BSD curses não é mais mantida, tendo sido substituída " +"pela ncursess, que é uma implementação de código aberto da interface da " +"AT&T. Se você estiver usando um sistema operacional de código aberto baseado " +"em Unix, tal como Linux ou FreeBSD, seu sistema provavelmente usa ncurses. " +"Uma vez que a maioria das versões comerciais do Unix são baseadas no código " +"do System V, todas as funções descritas aqui provavelmente estarão " "disponíveis. No entanto, as versões antigas de curses carregadas por alguns " -"Unixes proprietários podem não suportar tudo." +"Unixes proprietários podem não prover tudo." #: ../../howto/curses.rst:58 msgid "" "The Windows version of Python doesn't include the :mod:`curses` module. A " "ported version called :pypi:`UniCurses` is available." msgstr "" +"A versão do Python para Windows não inclui o módulo :mod:`curses`. Uma " +"versão portada chamada :pypi:`UniCurses` está disponível." #: ../../howto/curses.rst:63 msgid "The Python curses module" @@ -157,6 +163,13 @@ msgid "" "mvwaddstr` into a single :meth:`~curses.window.addstr` method. You'll see " "this covered in more detail later." msgstr "" +"O módulo Python é um invólucro razoavelmente simples sobre as funções C " +"disponibilizadas pela curses; Se você já estiver familiarizado com " +"programação curses em C, é bem fácil transmitir esse conhecimento para o " +"Python. A maior diferença é que a interface Python simplifica as coisas ao " +"juntar diferentes funções C como :c:func:`!addstr`, :c:func:`!mvaddstr` e :c:" +"func:`!mvwaddstr` em um único método :meth:`~curses.window.addstr`. Veremos " +"isso mais adiante." #: ../../howto/curses.rst:73 msgid "" @@ -165,10 +178,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" @@ -183,6 +196,20 @@ msgid "" "object representing the entire screen; this is usually called ``stdscr`` " "after the name of the corresponding C variable. ::" msgstr "" +"Antes de qualquer coisas, a curses precisa ser inicializada. Para isso, " +"chame a função :func:`~curses.initscr`, que vai determinar o tipo do " +"terminal, enviar para ele quaisquer códigos de inicialização necessários, e " +"criar várias estruturas de dados internas. Se bem-sucedida, a :func:`!" +"initscr` retorna um objeto de janela representando a tela inteira; ele é " +"comumente chamado ``stdscr`` por causa da variável C correspondente. ::" + +#: ../../howto/curses.rst:90 +msgid "" +"import curses\n" +"stdscr = curses.initscr()" +msgstr "" +"import curses\n" +"stdscr = curses.initscr()" #: ../../howto/curses.rst:93 msgid "" @@ -191,9 +218,13 @@ msgid "" "circumstances. This requires calling the :func:`~curses.noecho` function. ::" msgstr "" "Geralmente aplicações curses desativam o envio automático de teclas para a " -"tela, para que seja possível ler chaves e somente exibi-las sob certas " +"tela, para que seja possível ler teclas e exibi-las somente sob certas " "circunstâncias. Isto requer a chamada da função :func:`~curses.noecho`. ::" +#: ../../howto/curses.rst:98 +msgid "curses.noecho()" +msgstr "curses.noecho()" + #: ../../howto/curses.rst:100 msgid "" "Applications will also commonly need to react to keys instantly, without " @@ -204,6 +235,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 "curses.cbreak()" + #: ../../howto/curses.rst:106 msgid "" "Terminals usually return special keys, such as the cursor keys or navigation " @@ -220,6 +255,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 "stdscr.keypad(True)" + #: ../../howto/curses.rst:115 msgid "" "Terminating a curses application is much easier than starting one. You'll " @@ -228,15 +267,29 @@ 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 "" +"curses.nocbreak()\n" +"stdscr.keypad(False)\n" +"curses.echo()" + #: ../../howto/curses.rst:122 msgid "" "to reverse the curses-friendly terminal settings. Then call the :func:" "`~curses.endwin` function to restore the terminal to its original operating " "mode. ::" msgstr "" -"para reverter as configurações de terminal amigáveis da curses. Então chame " -"a função :func:`~curses.endwin` para restaurar o terminal para seu modo de " -"operação original. ::" +"para reverter as configurações de terminal usadas pela biblioteca curses. " +"Então, chame 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 "curses.endwin()" #: ../../howto/curses.rst:128 msgid "" @@ -246,12 +299,12 @@ msgid "" "raises an uncaught exception. Keys are no longer echoed to the screen when " "you type them, for example, which makes using the shell difficult." msgstr "" -"Um problema comum ao debugar uma aplicação curses é deixar seu terminal " +"Um problema comum ao depurar uma aplicação curses é deixar seu terminal " "bagunçado quando a aplicação para sem restaurar o terminal ao seu estado " "anterior. Em Python isto comumente acontece quando seu código está com " -"problemas e eleva uma exceção não capturada. As teclas não são mais enviadas " -"para a tela quando você as digita, por exemplo, o que torna difícil utilizar " -"o shell." +"problemas e levanta uma exceção não capturada. As teclas não são mais " +"enviadas para a tela quando você as digita, por exemplo, o que torna difícil " +"utilizar o shell." #: ../../howto/curses.rst:134 msgid "" @@ -262,6 +315,40 @@ 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 "" +"from curses import wrapper\n" +"\n" +"def main(stdscr):\n" +" # Limpa a tela\n" +" stdscr.clear()\n" +"\n" +" # Levanta ZeroDivisionError quando i == 10.\n" +" for i in range(0, 11):\n" +" v = i-10\n" +" stdscr.addstr(i, 0, '10 dividido por {} é {}'.format(v, 10/v))\n" +"\n" +" stdscr.refresh()\n" +" stdscr.getkey()\n" +"\n" +"wrapper(main)" + #: ../../howto/curses.rst:153 msgid "" "The :func:`~curses.wrapper` function takes a callable object and does the " @@ -274,6 +361,14 @@ msgid "" "funny state on exception and you'll be able to read the exception's message " "and traceback." msgstr "" +"A função :func:`~curses.wrapper` leva um objeto chamável e faz as " +"inicializações descritas acima, inicializando também as cores se o terminal " +"as prover. A :func:`!wrapper` então roda o chamável. Quando ele retornar, a :" +"func:`!wrapper` vai restaurar o estado original do terminal. O chamável é " +"chamado dentro de um bloco :keyword:`try`...\\ :keyword:`except` que captura " +"exceções, restaura o estado do terminal, e então as levanta novamente. Dessa " +"forma, o seu terminal não vai ser deixado em nenhum estado engraçadinho caso " +"haja qualquer erro, e você poderá ler a mensagem e o traceback da exceção." #: ../../howto/curses.rst:165 msgid "Windows and Pads" @@ -286,8 +381,8 @@ msgid "" "it, allow the user to input strings, and so forth." msgstr "" "Janelas são a abstração mais básica em curses. Uma objeto janela representa " -"uma área retangular da tela, e suporta métodos para exibir texto, apagá-lo, " -"e permitir ai usuário inserir strings, e assim por diante." +"uma área retangular da tela, e provê métodos para exibir texto, apagá-lo, e " +"permitir ao usuário inserir strings, e assim por diante." #: ../../howto/curses.rst:171 msgid "" @@ -305,6 +400,16 @@ 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 "" +"begin_x = 20; begin_y = 7\n" +"height = 5; width = 40\n" +"win = curses.newwin(height, width, begin_y, begin_x)" + #: ../../howto/curses.rst:182 msgid "" "Note that the coordinate system used in curses is unusual. Coordinates are " @@ -330,7 +435,7 @@ msgid "" msgstr "" "Sua aplicação pode determinar o tamanho da tela usando as variáveis :data:" "`curses.LINES` e :data:`curses.COLS` para obter os tamanhos *y* e *x*. " -"Coordenadas legais estenderão de ``(0,0)`` a ``(curses.LINES - 1, curses." +"Coordenadas válidas vão variar de ``(0,0)`` até ``(curses.LINES - 1, curses." "COLS - 1)``." #: ../../howto/curses.rst:195 @@ -353,6 +458,13 @@ msgid "" "window and then clears the window, there's no need to send the original text " "because they're never visible." msgstr "" +"Isso é porque a curses foi desenvolvida originalmente no contexto de " +"conexões lentas de até 300 Bauds com o terminal; para esses terminais, " +"minimizar o tempo necessário para redesenhar a tela era importantíssimo. No " +"lugar disso, a curses acumula mudanças na tela, e as exibe da forma mais " +"eficiente possível quando você chama :meth:`!refresh`. Por exemplo, se o seu " +"programa mostra um texto em uma janela e então limpa a janela, não tem " +"porque enviar o texto original já que ele nunca seria visível." #: ../../howto/curses.rst:209 msgid "" @@ -363,6 +475,13 @@ msgid "" "redrawn before pausing to wait for user input, by first calling :meth:`!" "stdscr.refresh` or the :meth:`!refresh` method of some other relevant window." msgstr "" +"Na prática, ficar pedindo ao curses explicitamente para redesenhar a tela " +"não torna a programação com ele tão complicada assim. A maioria dos " +"programas faz uma enxurrada de atividades, e então pausa esperando uma tecla " +"digitada ou alguma outra ação por parte do usuário. Tudo que você deve fazer " +"é garantir que a tela foi redesenhada antes de pausar esperando pela entrada " +"do usuário, chamando antes a :meth:`!stdscr.refresh` ou o método :meth:`!" +"refresh` de alguma outra janela apropriada." #: ../../howto/curses.rst:217 msgid "" @@ -377,6 +496,39 @@ 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 "" +"pad = curses.newpad(100, 100)\n" +"# Estes laços preenchem o pad com letras; a addch()\n" +"# é explicada na seção a seguir.\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" +"# Exibe um pedaço de um pad no meio da tela.\n" +"# (0,0) : coordenada do canto superior esquerdo da área do pad a ser\n" +"# exibida.\n" +"# (5,5) : coordenada do canto superior esquerdo da área da janela a ser\n" +"# preenchida com o conteúdo do pad.\n" +"# (20, 75) : coordenada inferior direita da área da janela a ser\n" +"# : preenchida com o conteúdo do pad.\n" +"pad.refresh( 0,0, 5,5, 20,75)" + #: ../../howto/curses.rst:238 msgid "" "The :meth:`!refresh` call displays a section of the pad in the rectangle " @@ -385,6 +537,10 @@ msgid "" "Beyond that difference, pads are exactly like ordinary windows and support " "the same methods." msgstr "" +"A chamada da :meth:`!refresh` exibe um pedaço do pad no retângulo que vai da " +"coordenada (5,5) à coordenada (20,75) da tela; o canto superior esquerdo do " +"pedaço exibido corresponde à coordenada (0,0) do pad. Fora essa diferença, " +"pads são exatamente como janelas comuns, e provêm os mesmos métodos." #: ../../howto/curses.rst:244 msgid "" @@ -392,6 +548,10 @@ msgid "" "way to update the screen and prevent annoying screen flicker as each part of " "the screen gets updated. :meth:`!refresh` actually does two things:" msgstr "" +"Se você tem múltiplas janelas e pads na tela, existe um modo mais eficiente " +"de atualizar a tela que evita as cintilações irritantes que ocorrem à medida " +"que cada parte da tela vai sendo atualizada. O :meth:`!refresh` na verdade " +"faz duas coisas:" #: ../../howto/curses.rst:249 msgid "" @@ -408,13 +568,16 @@ msgid "" "screen to match the desired state recorded in the data structure." msgstr "" "Chama a função :func:`~curses.doupdate` para modificar a tela física para " -"corresponder com o estado original na estrutura de dados." +"corresponder com o estado desejado presente na estrutura de dados." #: ../../howto/curses.rst:255 msgid "" "Instead you can call :meth:`!noutrefresh` on a number of windows to update " "the data structure, and then call :func:`!doupdate` to update the screen." msgstr "" +"Em vez disso você pode chamar :meth:`!noutrefresh` em várias janelas para " +"atualizar a estrutura de dados, e então chamar :func:`!doupdate` para " +"atualizar a tela." #: ../../howto/curses.rst:261 msgid "Displaying Text" @@ -431,6 +594,14 @@ msgid "" "default. :c:func:`!mvwaddstr` allows specifying both a window and a " "coordinate." msgstr "" +"Do ponto de vista de um programador C, a curses à vezes pode parecer como um " +"labirinto sinuoso de funções, todas ligeiramente diferentes. Por exemplo, :c:" +"func:`!addstr` exibe uma string na posição atual do cursor na janela " +"``stdscr``, enquanto :c:func:`!mvaddstr` primeiro move o cursor para uma " +"dada coordenada y,x antes de exibir a string. A :c:func:`!waddstr` é como a :" +"c:func:`!addstr`, mas permite especificar uma janela para utilizar em vez de " +"usar a ``stdscr`` por padrão. A :c:func:`!mvwaddstr` permite especificar " +"tanto uma janela quanto uma coordenada." #: ../../howto/curses.rst:272 msgid "" @@ -509,6 +680,11 @@ msgid "" "window's :attr:`~window.encoding` attribute; this defaults to the default " "system encoding as returned by :func:`locale.getencoding`." msgstr "" +"O método :meth:`~curses.window.addstr` recebe uma string ou bytestring " +"Python como valor a ser exibido. os conteúdos de bytestrings são enviados ao " +"terminal tais como estão. Strings são codificadas em bytes usando o valor do " +"atributo :attr:`~window.encoding` da janela; o valor padrão usado é a " +"codificação padrão do sistema como retornado por :func:`locale.getencoding`." #: ../../howto/curses.rst:305 msgid "" @@ -576,6 +752,11 @@ msgid "" "to highlight certain words. curses supports this by allowing you to specify " "an attribute for each cell on the screen." msgstr "" +"Caracteres podem ser exibidos de diferentes formas. Linhas de status em " +"aplicações baseadas em texto são tradicionalmente exibidas em vídeo reverso, " +"ou um visualizador de texto pode precisar destacar certas palavras. Para " +"isso, a curses permite que você especifique um atributo para cada célula na " +"tela." #: ../../howto/curses.rst:338 msgid "" @@ -586,6 +767,12 @@ msgid "" "being used, so it's safest to stick to the most commonly available " "attributes, listed here." msgstr "" +"Um atributo é um inteiro em que cada bit representa um atributo diferente. " +"Você sempre pode tentar exibir texto com múltiplos bits de atributo ligados " +"ao mesmo tempo, mas a curses não garante que todas as combinações possíveis " +"estarão disponíveis, ou que elas são todas visualmente distintas. Isso " +"depende da habilidade do terminal sendo usado, de forma que é mais seguro se " +"ater aos atributos mais comumente disponíveis, listados aqui." #: ../../howto/curses.rst:346 msgid "Attribute" @@ -597,7 +784,7 @@ msgstr ":const:`A_BLINK`" #: ../../howto/curses.rst:348 msgid "Blinking text" -msgstr "" +msgstr "Texto piscante" #: ../../howto/curses.rst:350 msgid ":const:`A_BOLD`" @@ -605,7 +792,7 @@ msgstr ":const:`A_BOLD`" #: ../../howto/curses.rst:350 msgid "Extra bright or bold text" -msgstr "" +msgstr "Texto em negrito ou brilho extra" #: ../../howto/curses.rst:352 msgid ":const:`A_DIM`" @@ -613,7 +800,7 @@ msgstr ":const:`A_DIM`" #: ../../howto/curses.rst:352 msgid "Half bright text" -msgstr "" +msgstr "Texto em brilho médio" #: ../../howto/curses.rst:354 msgid ":const:`A_REVERSE`" @@ -621,7 +808,7 @@ msgstr ":const:`A_REVERSE`" #: ../../howto/curses.rst:354 msgid "Reverse-video text" -msgstr "" +msgstr "Texto em vídeo reverso" #: ../../howto/curses.rst:356 msgid ":const:`A_STANDOUT`" @@ -629,7 +816,7 @@ msgstr ":const:`A_STANDOUT`" #: ../../howto/curses.rst:356 msgid "The best highlighting mode available" -msgstr "" +msgstr "O modo mais destacado disponível" #: ../../howto/curses.rst:358 msgid ":const:`A_UNDERLINE`" @@ -644,6 +831,18 @@ msgid "" "So, to display a reverse-video status line on the top line of the screen, " "you could code::" msgstr "" +"Assim, pra exibir uma linha de status em vídeo reverso na linha no topo da " +"tela, você poderia escrever::" + +#: ../../howto/curses.rst:364 +msgid "" +"stdscr.addstr(0, 0, \"Current mode: Typing mode\",\n" +" curses.A_REVERSE)\n" +"stdscr.refresh()" +msgstr "" +"stdscr.addstr(0, 0, \"Modo atual: Modo de digitação\",\n" +" curses.A_REVERSE)\n" +"stdscr.refresh()" #: ../../howto/curses.rst:368 msgid "" @@ -651,6 +850,9 @@ msgid "" "The most common such terminal is probably the Linux console, followed by " "color xterms." msgstr "" +"A biblioteca curses também permite o uso de cores nos terminais que as " +"provêm. Destes, o terminal mais comum é provavelmente o console Linux, " +"seguido pelos xterms com cores." #: ../../howto/curses.rst:372 msgid "" @@ -663,6 +865,14 @@ msgid "" "to the British spelling, you'll have to resign yourself to misspelling it " "for the sake of these functions.)" msgstr "" +"Para usar cores, você deve chamar a função :func:`~curses.start_color` logo " +"depois de chamar :func:`~curses.initscr`, para inicializar a paleta de cores " +"padrão (a função :func:`curses.wrapper` faz isso automaticamente.) Uma vez " +"feito isso, a função :func:`~curses.has_colors` retorna True se o terminal " +"em uso de fato suportar cores. (Nota: a curses usa a grafia Americana " +"'color' ao invés da grafia Britânica/Canadense 'colour.' Se você estiver " +"acostumado com a grafia Britânica, você terá que se resignar a escrever com " +"a grafia trocada ao chamar essas funções.)" #: ../../howto/curses.rst:382 msgid "" @@ -673,10 +883,24 @@ msgid "" "as :const:`A_REVERSE`, but again, such combinations are not guaranteed to " "work on all terminals." msgstr "" +"A biblioteca curses mantém uma quantidade finita de pares de cores, contendo " +"uma cor de primeiro plano (ou de texto) e uma de fundo. Você pode obter o " +"valor do atributo correspondente a um par de cores com a função :func:" +"`~curses.color_pair`; esse valor pode ser combinado com OU (OR) bit a bit " +"com outros atributos como :const:`A_REVERSE`, mas, novamente, não é " +"garantido que tais combinações vão funcionar em todos os terminais." #: ../../howto/curses.rst:389 msgid "An example, which displays a line of text using color pair 1::" +msgstr "Um exemplo, exibindo uma linha de texto com o par de cores 1::" + +#: ../../howto/curses.rst:391 +msgid "" +"stdscr.addstr(\"Pretty text\", curses.color_pair(1))\n" +"stdscr.refresh()" msgstr "" +"stdscr.addstr(\"Texto colorido\", curses.color_pair(1))\n" +"stdscr.refresh()" #: ../../howto/curses.rst:394 msgid "" @@ -685,6 +909,10 @@ msgid "" "pair *n*, to foreground color f and background color b. Color pair 0 is " "hard-wired to white on black, and cannot be changed." msgstr "" +"Como dito anteriormente, um par de cores consiste de uma cor de primeiro " +"plano e uma cor de fundo. A função ``init_pair(n, f, b)`` muda a definição " +"do par de cores *n* para a cor de primeiro plano *f* e cor de fundo *b*. O " +"par 0 é pré-definido como branco sobre preto, e não pode ser mudado." #: ../../howto/curses.rst:399 msgid "" @@ -694,12 +922,23 @@ msgid "" "named constants for each of these colors: :const:`curses.COLOR_BLACK`, :" "const:`curses.COLOR_RED`, and so forth." msgstr "" +"As cores são numeradas, e a :func:`start_color` inicializa 8 cores básicas " +"ao ativar o modo colorido. São elas: 0:preto, 1:vermelho, 2:verde, 3:" +"amarelo, 4:azul, 5:magenta, 6:ciano e 7:branco. O módulo :mod:`curses` " +"define constantes nomeadas para cada uma dessas cores: :const:`curses." +"COLOR_BLACK`, :const:`curses.COLOR_RED`, e assim por diante." #: ../../howto/curses.rst:405 msgid "" "Let's put all this together. To change color 1 to red text on a white " "background, you would call::" msgstr "" +"Vamos juntar tudo isso. Para redefinir a cor 1 como texto vermelho sobre " +"fundo branco, você chamaria::" + +#: ../../howto/curses.rst:408 +msgid "curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)" +msgstr "curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)" #: ../../howto/curses.rst:410 msgid "" @@ -707,6 +946,13 @@ msgid "" "pair will change to the new colors. You can also display new text in this " "color with::" msgstr "" +"Quando você redefine um par de cores, qualquer texto que já tenha sido " +"exibido usando esse par de cores vai mudar para a nova definição. Você pode " +"também exibir mais texto nessa nova cor com::" + +#: ../../howto/curses.rst:414 +msgid "stdscr.addstr(0,0, \"RED ALERT!\", curses.color_pair(1))" +msgstr "stdscr.addstr(0,0, \"ALERTA VERMELHO!\", curses.color_pair(1))" #: ../../howto/curses.rst:416 msgid "" @@ -719,6 +965,15 @@ msgid "" "there. If you're lucky enough to have such a talented terminal, consult " "your system's man pages for more information." msgstr "" +"Terminais super sofisticados podem trocar as definições das cores em si para " +"um dado valor RGB. Isso permite que você troque a cor 1, que geralmente é " +"vermelha, para roxo ou azul ou qualquer outra cor que você queira. " +"Infelizmente, o terminal Linux não provê essa funcionalidade, de forma que " +"eu não consigo testá-la para fornecer exemplos. Você pode verificar se o seu " +"terminal tem esse recurso chamando a função :func:`~curses." +"can_change_color`, que retorna ``True`` se o recurso existir. Se por ventura " +"o seu terminal for talentoso assim, consulte as páginas man do seu sistema " +"para mais informações." #: ../../howto/curses.rst:427 msgid "User Input" @@ -730,10 +985,14 @@ msgid "" "`curses` module adds a basic text-input widget. (Other libraries such as :" "pypi:`Urwid` have more extensive collections of widgets.)" msgstr "" +"A biblioteca curses em C oferece somente mecanismos de entrada muito " +"simples. O módulo :mod:`curses` do Python adiciona um componente básico de " +"entrada de texto. (Outras bibliotecas como :pypi:`Urwid` têm coleções mais " +"extensas de componentes.)" #: ../../howto/curses.rst:433 msgid "There are two methods for getting input from a window:" -msgstr "" +msgstr "Há dois métodos para capturar entrada de uma janela:" #: ../../howto/curses.rst:435 msgid "" @@ -742,6 +1001,10 @@ msgid "" "called earlier. You can optionally specify a coordinate to which the cursor " "should be moved before pausing." msgstr "" +"O :meth:`~curses.window.getch` atualiza a tela e então espera o usuário " +"apertar alguma tecla, exibindo o valor dela caso :func:`~curses.echo` tenha " +"sido chamada anteriormente. Opcionalmente, você pode especificar a " +"coordenada onde o cursor deve ser posicionado antes de pausar." #: ../../howto/curses.rst:440 msgid "" @@ -750,6 +1013,10 @@ msgid "" "special keys such as function keys return longer strings containing a key " "name such as ``KEY_UP`` or ``^G``." msgstr "" +"O :meth:`~curses.window.getkey` faz a mesma coisa, mas converte o inteiro " +"para string. Caracteres individuais são retorndos como strings de 1 " +"caractere, e teclas especiais como teclas funcionais retornam strings " +"maiores contendo nomes de teclas como ``KEY_UP`` ou ``^G``." #: ../../howto/curses.rst:445 msgid "" @@ -762,6 +1029,15 @@ msgid "" "getch`; if no input becomes available within a specified delay (measured in " "tenths of a second), curses raises an exception." msgstr "" +"É possível não esperar pelo usuário usando o método :meth:`~curses.window." +"nodelay` das janelas. Após ``nodelay(True)``, os métodos :meth:`!getch` e :" +"meth:`!getkey` da janela viram não-bloqueantes. Para sinalizar que não há " +"entrada disponível, o :meth:`!getch` retorna ``curses.ERR`` (com valor de " +"-1) e o :meth:`!getkey` levanta uma exceção. Também há uma função :func:" +"`~curses.halfdelay`, que pode ser usada para (efetivamente) definit um " +"temporizador em cada :meth:`!getch`; se nenhuma entrada estiver disponível " +"após um intervalo de espera especificado (medido em décimos de segundo), a " +"curses levanta uma exceção." #: ../../howto/curses.rst:455 msgid "" @@ -772,6 +1048,32 @@ msgid "" "`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. The main loop of your " "program may look something like this::" msgstr "" +"O método :meth:`!getch` retorna um inteiro. Se ele estiver entre 0 e 255, " +"ele representa o código ASCII da tecla digitada. Valores maiores que 255 são " +"teclas especiais como Page Up, Home, ou as teclas de seta. Você pode " +"comparar o valor retornado com constantes como :const:`curses.KEY_PPAGE`, :" +"const:`curses.KEY_HOME` ou :const:`curses.KEY_LEFT`. O laço principal do seu " +"programa pode ser algo como::" + +#: ../../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 "" +"while True:\n" +" c = stdscr.getch()\n" +" if c == ord('p'):\n" +" PrintDocument()\n" +" elif c == ord('q'):\n" +" break # Interrompe o laço while\n" +" elif c == curses.KEY_HOME:\n" +" x = y = 0" #: ../../howto/curses.rst:471 msgid "" @@ -782,6 +1084,13 @@ msgid "" "arguments and return the same type. For example, :func:`curses.ascii.ctrl` " "returns the control character corresponding to its argument." msgstr "" +"O módulo :mod:`curses.ascii` fornece funções de teste de pertencimento que " +"levam como argumento tanto inteiros quanto strings de 1 caractere; elas " +"podem ser úteis para escrever testes mais legíveis para tais laços. Ele " +"também fornece funções de conversão que levam como argumento tanto inteiros " +"quanto strings de 1 caractere, e retornam objetos do mesmo tipo. Por " +"exemplo, :func:`curses.ascii.ctrl` retorna o caractere de controle " +"correspondente ao argumento." #: ../../howto/curses.rst:478 msgid "" @@ -791,6 +1100,23 @@ msgid "" "key, which terminates the string. It can optionally be limited to a fixed " "number of characters. ::" msgstr "" +"Também há um método para pegar uma string inteira, :meth:`~curses.window." +"getstr`. Ele não costuma ser usado porque a sua funcionalidade é um pouco " +"limitada: as únicas teclas de edição disponíveis são o Backspace e o Enter, " +"que termina a string. Ele pode opcionalmente limitado a um número fixo de " +"caracteres. ::" + +#: ../../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 "" +"curses.echo() # Abilita visualização dos caracteres\n" +"\n" +"# Lê uma string de 15 caracteres, com o cursor na linha do topo\n" +"s = stdscr.getstr(0,0, 15)" #: ../../howto/curses.rst:489 msgid "" @@ -799,11 +1125,57 @@ msgid "" "Textbox` class support editing with input validation and gathering the edit " "results either with or without trailing spaces. Here's an example::" msgstr "" +"O módulo :mod:`curses.textpad` fornece uma caixa de texto que provê um " +"conjunto de atalhos de teclado estilo Emacs. Vários métodos da classe :class:" +"`~curses.textpad.Textbox` provêm edição com validação de entrada e " +"recuperação dos resultados da edição com ou sem espaços em branco no final." + +#: ../../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 "" +"import curses\n" +"from curses.textpad import Textbox, rectangle\n" +"\n" +"def main(stdscr):\n" +" stdscr.addstr(\n" +" 0, 0,\n" +" \"Digite a mensagem instantânea: (aperte Ctrl-G para enviar)\")\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" +" # Deixa o usuário editar até apertar Ctrl-G.\n" +" box.edit()\n" +"\n" +" # Recupera o conteúdo resultante.\n" +" message = box.gather()" #: ../../howto/curses.rst:513 msgid "" "See the library documentation on :mod:`curses.textpad` for more details." msgstr "" +"Consulte a documentação de biblioteca do :mod:`curses.textpad` para mais " +"detalhes." #: ../../howto/curses.rst:517 msgid "For More Information" @@ -816,6 +1188,10 @@ msgid "" "Python library page for the :mod:`curses` module is now reasonably " "complete. You should browse it next." msgstr "" +"Este COMOFAZER não cobre alguns tópicos avançados, como ler o conteúdo da " +"tela ou capturar eventos de mouse de uma instância xterm, mas a página de " +"biblioteca Python para o módulo :mod:`curses` está agora razoavelmente " +"completa. Ela deve ser o seu próximo destino." #: ../../howto/curses.rst:524 msgid "" @@ -825,6 +1201,12 @@ msgid "" "quirks, and provide complete lists of all the functions, attributes, and :" "ref:`ACS_\\* ` characters available to you." msgstr "" +"Se estiver em dúvida quanto aos detalhes do comportamento das funções " +"curses, consulte as páginas de manual para a sua implementação curses, seja " +"ela o ncurses ou de algum fornecedor Unix proprietário. As páginas de manual " +"vão documentar quaisquer peculiaridades, e prover listas completas de todas " +"as funções, atributos e caracteres :ref:`ACS_\\* ` " +"disponíveis para você." #: ../../howto/curses.rst:531 msgid "" @@ -835,21 +1217,31 @@ msgid "" "would be welcome; see `the Python Developer's Guide `_ to learn more about submitting patches to Python." msgstr "" +"Devido à API da curses ser tão grande, algumas funções não são providas pela " +"interface Python. Muitas vezes isso não é por dificuldade de implementação, " +"e sim porque ninguém precisou delas ainda. Além disso, o Python ainda não " +"suporta a biblioteca de menus associada à ncurses. Patches que adicionem " +"suporte a essas funcionalidades seriam bem-vindos; veja `o Guia do " +"Desenvolvedor do Python `_ para aprender " +"melhor sobre como submeter patches ao Python." #: ../../howto/curses.rst:539 msgid "" "`Writing Programs with NCURSES `_: a lengthy tutorial for C programmers." msgstr "" +"`Writing Programs with NCURSES `_: um tutorial comprido para programadores C." #: ../../howto/curses.rst:541 msgid "`The ncurses man page `_" -msgstr "" +msgstr "`Página man do ncurses `_" #: ../../howto/curses.rst:542 msgid "" "`The ncurses FAQ `_" msgstr "" +"`FAQ do ncurses `_" #: ../../howto/curses.rst:543 msgid "" @@ -857,6 +1249,9 @@ msgid "" "v=eN1eZtjLEnU>`_: video of a PyCon 2013 talk on controlling terminals using " "curses or Urwid." msgstr "" +"`\"Use curses... don't swear\" `_: vídeo de uma palestra na PyCon 2013 sobre controle de " +"terminais usando curses ou Urwid." #: ../../howto/curses.rst:545 msgid "" @@ -864,3 +1259,6 @@ msgid "" "applications-with-urwid>`_: video of a PyCon CA 2012 talk demonstrating some " "applications written using Urwid." msgstr "" +"`\"Console Applications with Urwid\" `_: vídeo de uma palestra na PyCon CA 2012 " +"demonstrando algumas aplicações escritas com Urwid." diff --git a/howto/descriptor.po b/howto/descriptor.po index f9d3146b6..b405f26ca 100644 --- a/howto/descriptor.po +++ b/howto/descriptor.po @@ -1,34 +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 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2021 -# i17obot , 2021 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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" @@ -67,9 +65,9 @@ msgid "" "The \"primer\" gives a basic overview, moving gently from simple examples, " "adding one feature at a time. Start here if you're new to descriptors." msgstr "" -"O \"primer\" oferece uma visão geral básica, movendo-se suavemente a partir " -"de exemplos simples, adicionando um recurso de cada vez. Comece aqui se você " -"for novo em descritores." +"A \"introdução\" oferece uma visão geral básica, movendo-se suavemente a " +"partir de exemplos simples, adicionando um recurso de cada vez. Comece aqui " +"se você for novo em descritores." #: ../../howto/descriptor.rst:21 msgid "" @@ -104,15 +102,15 @@ msgstr "" #: ../../howto/descriptor.rst:36 msgid "Primer" -msgstr "Primer" +msgstr "Introdução" #: ../../howto/descriptor.rst:38 msgid "" "In this primer, we start with the most basic possible example and then we'll " "add new capabilities one by one." msgstr "" -"Neste primer, começamos com o exemplo mais básico possível e, em seguida, " -"adicionaremos novos recursos um por um." +"Nesta introdução, começamos com o exemplo mais básico possível e, em " +"seguida, adicionaremos novos recursos um por um." #: ../../howto/descriptor.rst:43 msgid "Simple example: A descriptor that returns a constant" @@ -120,9 +118,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 +142,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 +160,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 +181,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 +220,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 +258,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 +311,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 +330,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 +392,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 +476,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 +616,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 +641,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 +668,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 +679,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 +707,296 @@ 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 "" - -#: ../../howto/descriptor.rst:437 -msgid "Practical application" +":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 a 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 "" #: ../../howto/descriptor.rst:439 -msgid "Here's how the data validators can be used in a real class:" -msgstr "" +msgid "Practical application" +msgstr "Aplicação prática" -#: ../../howto/descriptor.rst:454 +#: ../../howto/descriptor.rst:441 +msgid "Here's how the data validators can be used in a real class:" +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 +1007,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 +1076,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: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:968 +#: ../../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 +1754,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:1273 +#: ../../howto/descriptor.rst:1248 +msgid "" +">>> d = D()\n" +">>> d.f\n" +">" +msgstr "" +">>> d = D()\n" +">>> d.f\n" +">" + +#: ../../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 +2108,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 +2123,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 +2189,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 +2233,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 +2291,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 +2372,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 +2415,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..ff0b14f32 100644 --- a/howto/enum.po +++ b/howto/enum.po @@ -1,48 +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: -# 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 +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# Marcos Moraes, 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-10-31 15:04+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Marcos Moraes, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +47,46 @@ 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 "" +">>> from enum import Enum\n" +">>> class DiaDaSemana(Enum):\n" +"... SEGUNDA = 1\n" +"... TERÇA = 2\n" +"... QUARTA = 3\n" +"... QUINTA = 4\n" +"... SEXTA = 5\n" +"... SÁBADO = 6\n" +"... DOMINGO = 7" + #: ../../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 "" +">>> from enum import Enum\n" +">>> class Cor(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3" + #: ../../howto/enum.rst:36 msgid "" "As you can see, creating an :class:`Enum` is as simple as writing a class " @@ -66,7 +97,7 @@ msgstr "" #: ../../howto/enum.rst:39 msgid "Case of Enum Members" -msgstr "Caso de membros de Enums" +msgstr "Maiúsculas em membros de Enums" #: ../../howto/enum.rst:41 msgid "" @@ -77,7 +108,7 @@ msgid "" msgstr "" "Como os Enums são usados para representar constantes, e para ajudar a evitar " "problemas com nomes conflitando entre métodos/atributos de classes mixin e " -"nomes enum, nós fortemente recomendamos o uso de nomes em UPPER_CASE(em " +"nomes enum, nós fortemente recomendamos o uso de nomes em UPPER_CASE (em " "caixa alta) para membros, e usaremos esse estilo em nossos exemplos." #: ../../howto/enum.rst:46 @@ -87,9 +118,17 @@ msgid "" "member::" msgstr "" "Dependendo da natureza do enum, o valor de um membro pode ou não ser " -"importante, mas de qualquer forma esse valor pode ser usado para obter o " +"importante. Mas, de qualquer forma, esse valor pode ser usado para obter o " "membro correspondente::" +#: ../../howto/enum.rst:50 +msgid "" +">>> Weekday(3)\n" +"" +msgstr "" +">>> DiaDaSemana(3)\n" +"" + #: ../../howto/enum.rst:53 msgid "" "As you can see, the ``repr()`` of a member shows the enum name, the member " @@ -100,143 +139,401 @@ 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 "" +">>> print(DiaDaSemana.QUINTA)\n" +"DiaDaSemana.QUINTA" + #: ../../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 "" +">>> type(DiaDaSemana.SEGUNDA)\n" +"\n" +">>> isinstance(DiaDaSemana.SEXTA, DiaDaSemana)\n" +"True" + #: ../../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 "" +"Os membros do Enum têm um atributo que contém apenas seu :attr:`!name`::" + +#: ../../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`::" +">>> print(DiaDaSemana.TERÇA.name)\n" +"TERÇA" #: ../../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 "Da mesma forma, eles têm um atributo para seu :attr:`!value`::" + +#: ../../howto/enum.rst:75 +msgid "" +">>> Weekday.WEDNESDAY.value\n" +"3" +msgstr "" +">>> DiaDaSemana.QUARTA.value\n" +"3" #: ../../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::" +"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 "" "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 +"semana: :meth:`~datetime.date.weekday` e :meth:`~datetime.date.isoweekday`. " +"A diferença é que um deles conta de 0 a 6 e o outro de 1 a 7. Em vez de " +"tomar conta disso nós mesmos, podemos adicionar um método ao enum de :class:" +"`!DiaDaSemana` para extrair o dia da instância de :class:`~datetime.date` e " +"retornar o membro enum correspondente::" + +#: ../../howto/enum.rst:87 +msgid "" +"@classmethod\n" +"def from_date(cls, date):\n" +" return cls(date.isoweekday())" +msgstr "" +"@classmethod\n" +"def from_date(cls, date):\n" +" return cls(date.isoweekday())" + +#: ../../howto/enum.rst:91 +msgid "The complete :class:`!Weekday` enum now looks like this::" +msgstr "A enum :class:`!DiaDaSemana` completa fica então assim:" + +#: ../../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 "" +">>> class DiaDaSemana(Enum):\n" +"... SEGUNDA = 1\n" +"... TERÇA = 2\n" +"... QUARTA = 3\n" +"... QUINTA = 4\n" +"... SEXTA = 5\n" +"... SÁBADO = 6\n" +"... DOMINGO = 7\n" +"... #\n" +"... @classmethod\n" +"... def from_date(cls, date):\n" +"... return cls(date.isoweekday())" + +#: ../../howto/enum.rst:106 msgid "Now we can find out what today is! Observe::" -msgstr "Agora podemos descobrir o que é hoje! Observar::" +msgstr "Agora podemos descobrir que dia é hoje! Observe::" + +#: ../../howto/enum.rst:108 +msgid "" +">>> from datetime import date\n" +">>> Weekday.from_date(date.today())\n" +"" +msgstr "" +">>> from datetime import date\n" +">>> DiaDaSemana.from_date(date.today())\n" +"" -#: ../../howto/enum.rst:111 +#: ../../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." +"Claro, se você estiver lendo isso em outro dia da semana, você verá esse " +"respectivo 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 +"Essa enum :class:`!DiaDaSemana` é ótima se a nossa variável precisar somente " +"de um único dia, mas e se precisarmos de vários? Talvez estejamos escrevendo " +"uma função para organizar tarefas ao longo da semana, e não queremos usar " +"uma :class:`list` -- poderíamos ao invés disso usar um tipo diferente de :" +"class:`Enum`:" + +#: ../../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 "" +">>> from enum import Flag\n" +">>> class DiaDaSemana(Flag):\n" +"... SEGUNDA = 1\n" +"... TERÇA = 2\n" +"... QUARTA = 4\n" +"... QUINTA = 8\n" +"... SEXTA = 16\n" +"... SÁBADO = 32\n" +"... DOMINGO = 64" + +#: ../../howto/enum.rst:129 msgid "" "We've changed two things: we're inherited from :class:`Flag`, and the values " "are all powers of 2." msgstr "" -"Nós mudamos duas coisas: estamos herdando de :class:`Flag`, e os valores são " -"todos potências de 2." +"Nós mudamos duas coisas: estamos herdando de :class:`Flag` (sinalizador), 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:" +"Assim como a enum :class:`!DiaDaSemana` original acima, podemos selecionar " +"um item de cada vez::" + +#: ../../howto/enum.rst:134 +msgid "" +">>> first_week_day = Weekday.MONDAY\n" +">>> first_week_day\n" +"" +msgstr "" +">>> primeiro_dia_útil = DiaDaSemana.SEGUNDA\n" +">>> primeiro_dia_útil\n" +"" -#: ../../howto/enum.rst:137 +#: ../../howto/enum.rst:138 msgid "" "But :class:`Flag` also allows us to combine several members into a single " "variable::" msgstr "" -"Porem :class:`Flag` também nos permite combinar vários membros em uma única " -"variável:" +"Porém, a :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 "" +">>> fim_de_semana = DiaDaSemana.SÁBADO | DiaDaSemana.DOMINGO\n" +">>> fim_de_semana\n" +"" + +#: ../../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`:" +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 "" +">>> for dia in fim_de_semana:\n" +"... print(dia)\n" +"DiaDaSemana.SÁBADO\n" +"DiaDaSemana.DOMINGO" + +#: ../../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 "" +">>> tarefas_do_joão = {\n" +"... 'alimentar o gato': DiaDaSemana.SEGUNDA | DiaDaSemana.QUARTA | " +"DiaDaSemana.SEXTA,\n" +"... 'lavar a louça': DiaDaSemana.TERÇA | DiaDaSemana.QUINTA,\n" +"... 'responder perguntas no SO': DiaDaSemana.SÁBADO,\n" +"... }" + +#: ../../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 "" -"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::" +">>> 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 "" -"Nos casos onde os valores reais dos membros não importam, você pode " -"economizar trabalho e usar :func:`auto()` para os valores:" +">>> def mostrar_tarefas(tarefas, dia):\n" +"... for tarefa, dias in tarefas.items():\n" +"... if dia in dias:\n" +"... print(tarefa)\n" +"...\n" +">>> mostrar_tarefas(tarefas_do_joão, DiaDaSemana.SÁBADO)\n" +"responder perguntas no SO" -#: ../../howto/enum.rst:188 +#: ../../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::" +msgstr "" +"Quando os valores em si dos membros não forem importantes, você pode " +"economizar trabalho e usar :func:`auto` para eles::" + +#: ../../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 "" +">>> from enum import auto\n" +">>> class DiaDaSemana(Flag):\n" +"... SEGUNDA = auto()\n" +"... TERÇA = auto()\n" +"... QUARTA = auto()\n" +"... QUINTA = auto()\n" +"... SEXTA = auto()\n" +"... SÁBADO = auto()\n" +"... DOMINGO = auto()\n" +"... FIM_DE_SEMANA = SÁBADO | DOMINGO" + +#: ../../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 " "known at program-writing time). ``Enum`` allows such access::" msgstr "" "Em alguns momentos, é util ter acesso aos membros na enumeração de forma " -"programática(ou seja, em situações em que ``Color.RED`` não é adequado " -"porque a cor exata não é conhecida no momento da escrita do programa)." -"``Enum`` permite esse tipo de acesso:" +"programática (ou seja, em situações em que ``Cor.RED`` não é adequado porque " +"a cor exata não é conhecida no momento da escrita do programa). Classes " +"``Enum`` permitem esse tipo de acesso::" -#: ../../howto/enum.rst:199 +#: ../../howto/enum.rst:195 +msgid "" +">>> Color(1)\n" +"\n" +">>> Color(3)\n" +"" +msgstr "" +">>> Cor(1)\n" +"\n" +">>> Cor(3)\n" +"" + +#: ../../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 "" +">>> Cor['VERMELHO']\n" +"\n" +">>> Color['VERDE']\n" +"" + +#: ../../howto/enum.rst:207 +msgid "" +"If you have an enum member and need its :attr:`!name` or :attr:`!value`::" +msgstr "" +"Dado um membro de um enum, se você precisar do seu :attr:`!name` ou :attr:`!" +"value`::" + +#: ../../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`:" +">>> membro = Cor.VERMELHO\n" +">>> membro.name\n" +"'VERMELHO'\n" +">>> membro.value\n" +"1" -#: ../../howto/enum.rst:216 +#: ../../howto/enum.rst:217 msgid "Duplicating enum members and values" -msgstr "Duplicar membros do enum e seus valores." +msgstr "Membros e valores duplicados em enums" -#: ../../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 "" +">>> class Forma(Enum):\n" +"... QUADRADO = 2\n" +"... QUADRADO = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: 'QUADRADO' already defined as 2" + +#: ../../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`` " @@ -244,13 +541,42 @@ msgid "" "will return the member ``A``. By-name lookup of ``A`` will return the " "member ``A``. By-name lookup of ``B`` will also return the member ``A``::" msgstr "" -"Porém, um membro do enum pode ter outros nomes associados a ele. Dado dois " +"Porém, um membro do enum pode ter outros nomes associados a ele. Dados dois " "membros ``A`` e ``B`` com o mesmo valor (e ``A`` definido primeiro), ``B`` é " -"um apelido para o membro ``A``. A pesquisa por valor de ``A`` retorna o " -"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 +"um apelido para o membro ``A``. A busca pelo membro associado ao valor de " +"``A`` retorna o membro ``A``. A busca pelo membro com o nome de ``A`` " +"retorna o membro ``A``. A busca pelo membro com o nome de ``B`` também " +"retorna o membro ``A``::" + +#: ../../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 "" +">>> class Forma(Enum):\n" +"... QUADRADO = 2\n" +"... DIAMANTE = 1\n" +"... CÍRCULO = 3\n" +"... APELIDO_PARA_O_QUADRADO = 2\n" +"...\n" +">>> Forma.QUADRADO\n" +"\n" +">>> Forma.APELIDO_PARA_O_QUADRADO\n" +"\n" +">>> Forma(2)\n" +"" + +#: ../../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 +586,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" +msgstr "Garantindo valores únicos na 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,106 +599,289 @@ 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 "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Errado(Enum):\n" +"... UM = 1\n" +"... DOIS = 2\n" +"... TRES = 3\n" +"... QUATRO = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : QUATRO -> TRES" + +#: ../../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 -msgid "" -"The values are chosen by :func:`_generate_next_value_`, which can be " +msgstr "Se o valor em si não é importante, você pode usar :class:`auto`::" + +#: ../../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 "" +">>> from enum import Enum, auto\n" +">>> class Cor(Enum):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> [membro.value for membro in Cor]\n" +"[1, 2, 3]" + +#: ../../howto/enum.rst:288 +msgid "" +"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 -msgid "" -"The :meth:`_generate_next_value_` method must be defined before any members." -msgstr "" -"O método :meth:`_generate_next_value_` deve ser definido antes de qualquer " -"membro." - -#: ../../howto/enum.rst:309 +"Os valores são escolhidos pelo :func:`~Enum._generate_next_value_`, que pode " +"ser substituído::" + +#: ../../howto/enum.rst:291 +msgid "" +">>> 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 "" +">>> class AutoName(Enum):\n" +"... @staticmethod\n" +"... def _generate_next_value_(name, start, count, last_values):\n" +"... return name\n" +"...\n" +">>> class Ordinal(AutoName):\n" +"... NORTE = auto()\n" +"... SUL = auto()\n" +"... LESTE = auto()\n" +"... OESTE = auto()\n" +"...\n" +">>> [membro.value for membro in Ordinal]\n" +"['NORTE', 'SUL', 'LESTE', 'OESTE']" + +#: ../../howto/enum.rst:307 +msgid "" +"The :meth:`~Enum._generate_next_value_` method must be defined before any " +"members." +msgstr "" +"O método :meth:`~Enum._generate_next_value_` deve ser definido antes de " +"qualquer membro." + +#: ../../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:" +msgstr "Iterar sobre os membros de um enum não fornece os apelidos::" + +#: ../../howto/enum.rst:314 +msgid "" +">>> list(Shape)\n" +"[, , ]\n" +">>> list(Weekday)\n" +"[, , , , , , ]" +msgstr "" +">>> list(Forma)\n" +"[, , ]\n" +">>> list(DiaDaSemana)\n" +"[, , , " +", , , " +"]" -#: ../../howto/enum.rst:318 +#: ../../howto/enum.rst:319 msgid "" "Note that the aliases ``Shape.ALIAS_FOR_SQUARE`` and ``Weekday.WEEKEND`` " "aren't shown." msgstr "" -"Note que os apelidos ``Shape.ALIAS_FOR_SQUARE`` e ``Weekday.WEEKEND`` não " -"são mostrados." +"Note que os apelidos ``Forma.APELIDO_PARA_O_QUADRADO`` e ``DiaDaSemana." +"FIM_DE_SEMANA`` 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, " "including the aliases::" msgstr "" -"O atributo especial ``__members__`` é um mapeamento ordenado somente leitura " -"de nomes para os membros. Isso inclui todos os nomes definidos na " -"enumeração, incluindo os apelidos:" +"O atributo especial ``__members__`` é um mapeamento ordenado de somente " +"leitura dos nomes para os membros. Isso inclui todos os nomes definidos na " +"enumeração, incluindo os apelidos::" + +#: ../../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 "" +">>> for nome, membroin Forma.__members__.items():\n" +"... nome, membro\n" +"...\n" +"('QUADRADO', )\n" +"('DIAMANTE', )\n" +"('CÍRCULO', )\n" +"('APELIDO_PARA_O_QUADRADO', )" -#: ../../howto/enum.rst:332 +#: ../../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::" msgstr "" "O atributo ``__members__`` pode ser usado para um acesso programático " -"detalhado aos membros da enumeração. Por exemplo, achar todos os apelidos:" +"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 "" +">>> [nome for nome, membro in Forma.__members__.items() if membro.name != " +"nome]\n" +"['APELIDO_PARA_O_QUADRADO']" + +#: ../../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 "" +"Apelidos em sinalizadores incluem valores com múltiplos itens ao mesmo " +"tempo, como ``3``, e nenhum item definido, isto é, ``0``." -#: ../../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 "" +">>> Color.VERMELHO is Color.VERMELHO\n" +"True\n" +">>> Color.VERMELHO is Color.AZUL\n" +"False\n" +">>> Color.VERMELHO is not Color.AZUL\n" +"True" -#: ../../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 "" +"Comparações ordenadas entre valores de enumerações *não* são suportadas. " +"Membros Enum não são inteiros (porém, veja `IntEnum`_ abaixo)::" -#: ../../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 "" +">>> Color.VERMELHO < Color.AZUL\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: '<' not supported between instances of 'Color' and 'Color'" + +#: ../../howto/enum.rst:365 msgid "Equality comparisons are defined though::" +msgstr "Entretanto, comparações de igualdade são definidas::" + +#: ../../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 "" +">>> Color.AZUL == Color.VERMELHO\n" +"False\n" +">>> Color.AZUL != Color.VERMELHO\n" +"True\n" +">>> Color.AZUL == Color.AZUL\n" +"True" -#: ../../howto/enum.rst:373 +#: ../../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 "" +"Comparações com valores que não sejam de enumeração sempre resultarão em " +"\"não igual\" (novamente, :class:`IntEnum` foi explicitamente projetado para " +"se comportar de maneira diferente, veja abaixo)::" -#: ../../howto/enum.rst:382 +#: ../../howto/enum.rst:378 +msgid "" +">>> Color.BLUE == 2\n" +"False" +msgstr "" +">>> Color.AZUL == 2\n" +"False" + +#: ../../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,151 +889,308 @@ 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 +"Enumeraçõ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 "" +"As regras para o que é permitido são: nomes que começam e terminam com " +"underline único são reservados para enum e não podem ser usados; todos os " +"outros atributos definidos dentro de uma enumeração irão se tornar membros " +"dessa enumeração, com exceção dos métodos especiais ( :meth:`~object." +"__str__`, :meth:`~object.__add__`, etc.), descritores (métodos também são " +"descritores), e nomes de variáveis listadas em :attr:`~Enum._ignore_`." -#: ../../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 "" +"Nota: se a sua enumeração define :meth:`~object.__new__` e/ou :meth:`~object." +"__init__`, qualquer valor(es) dado ao membro da enum será passado para esses " +"métodos. Veja `Planet`_, por exemplo." -#: ../../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 "" +"O método :meth:`~object.__new__`, se definido, é usado durante a criação dos " +"membros do Enum; em seguida, ele é substituído pelo :meth:`~object.__new__` " +"do Enum, que é usado após a criação da classe para buscar por membros " +"existentes. Consulte :ref:`new-vs-init` para mais detalhes." -#: ../../howto/enum.rst:444 +#: ../../howto/enum.rst:445 msgid "Restricted Enum subclassing" -msgstr "" +msgstr "Herança restrita de Enum" -#: ../../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 "" +"Uma nova classe :class:`Enum` deve ter uma classe enum base, até um tipo de " +"dado concreto, e quantas classes mixin baseadas em :class:`object` forem " +"necessárias. A ordem dessas classes base é::" -#: ../../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 " +"enumeração não define nenhum membro. Portanto is,so é 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 " "makes sense to allow sharing some common behavior between a group of " "enumerations. (See `OrderedEnum`_ for an example.)" msgstr "" +"Permitir a criação de subclasses de enums que definem membros levaria a " +"violação de alguns invariantes importantes de tipos e instâncias. Por outro " +"lado, faz sentido permitir o compartilhamento de algum comportamento comum " +"entre um grupo de enumerações. (Veja `OrderedEnum`_, por exemplo.)" -#: ../../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 "" +"Ao herdar de uma :class:`~dataclasses.dataclass`, o :meth:`~Enum.__repr__` " +"omite o nome da classe herdada. Por exemplo::" -#: ../../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 "" +"Use o argumento ``repr=False`` de :func:`~dataclasses.dataclass` para " +"utilizar o :func:`repr` padrão." -#: ../../howto/enum.rst:505 +#: ../../howto/enum.rst:506 msgid "" "Only the dataclass fields are shown in the value area, not the dataclass' " "name." msgstr "" +"Somente os campos da dataclass são exibidos na área de valor, e não o nome " +"da dataclass." -#: ../../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 " "produce very strange results at runtime, such as members being equal to each " "other::" msgstr "" +"Não há suporte a adicionar o decorador :func:`~dataclasses.dataclass` a :" +"class:`Enum` e suas subclasses. Isso não irá levantar erros, mas poderá " +"produzir resultados muito estranhos em tempo de execução, como membros sendo " +"considerados iguais entre si." + +#: ../../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:528 +#: ../../howto/enum.rst:529 msgid "Pickling" msgstr "Pickling" -#: ../../howto/enum.rst:530 +#: ../../howto/enum.rst:531 msgid "Enumerations can be pickled and unpickled::" +msgstr "Enumerações podem ser serializadas e desserializadas." + +#: ../../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:537 +#: ../../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 "" +"As restrições usuais para serialização se aplicam: enums serializáveis devem " +"ser definidas no nível mais alto de um módulo, já que para fazer a " +"desserialização eles devem ser importados daquele módulo." -#: ../../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:573 +#: ../../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: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 +1199,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:586 +msgid "" +">>> class Animal(Enum):\n" +"... ANT = 1\n" +"... BEE = 2\n" +"... CAT = 3\n" +"... DOG = 4\n" +"..." msgstr "" -#: ../../howto/enum.rst:592 +#: ../../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 +1228,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:616 +msgid "" +">>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')" msgstr "" -#: ../../howto/enum.rst:617 +#: ../../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 "['VERMELHO', 'VERDE', 'AZUL']" + +#: ../../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 +1343,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 +1409,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 +1423,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 +1550,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 +1630,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 +1679,239 @@ 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 " "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 " "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 "" +">>> class Color(Enum):\n" +"... _order_ = 'VERMELHO VERDE AZUL'\n" +"... VERMELHO = 1\n" +"... AZUL = 3\n" +"... VERDE = 2\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: member order does not match _order_:\n" +" ['VERMELHO', 'AZUL', 'VERDE']\n" +" ['VERMELHO', 'VERDE', 'AZUL']" -#: ../../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 +1921,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 +1954,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 +2209,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 +2278,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:1353 +msgid "Using a custom :meth:`~object.__new__`" +msgstr "" + +#: ../../howto/enum.rst:1355 +msgid "Using an auto-numbering :meth:`~object.__new__` would look like::" +msgstr "" -#: ../../howto/enum.rst:1354 -msgid "Using an auto-numbering :meth:`__new__` would look like::" +#: ../../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:1371 +#: ../../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:`~object.__new__` or :meth:`~object.__init__` is defined, the value " +"of the enum member will be passed to those methods::" +msgstr "" + +#: ../../howto/enum.rst:1511 msgid "" -"If :meth:`__new__` or :meth:`__init__` is defined, the value of the enum " -"member will be passed to those methods::" +">>> 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:1536 +#: ../../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..6b80a36dc 100644 --- a/howto/free-threading-extensions.po +++ b/howto/free-threading-extensions.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,13 +54,35 @@ msgstr "" "A API C do CPython expõe a macro ``Py_GIL_DISABLED``: na construção com " "threads livres ela está definida como ``1``, e na construção regular ela não " "está definida. Você pode usá-la para ativar o código que é executado apenas " -"na construção de threads livres::" +"na construção com 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 com threads livres */\n" +"#endif" + +#: ../../howto/free-threading-extensions.rst:28 +msgid "" +"On Windows, this macro is not defined automatically, but must be specified " +"to the compiler when building. The :func:`sysconfig.get_config_var` function " +"can be used to determine whether the current running interpreter had the " +"macro defined." +msgstr "" +"No Windows, esta macro não é definida automaticamente, mas deve ser " +"especificada ao compilador durante a compilação. A função :func:`sysconfig." +"get_config_var` pode ser usada para determinar se o interpretador em " +"execução tinha a macro definida." -#: ../../howto/free-threading-extensions.rst:27 +#: ../../howto/free-threading-extensions.rst:35 msgid "Module Initialization" msgstr "Inicialização de módulo" -#: ../../howto/free-threading-extensions.rst:29 +#: ../../howto/free-threading-extensions.rst:37 msgid "" "Extension modules need to explicitly indicate that they support running with " "the GIL disabled; otherwise importing the extension will raise a warning and " @@ -71,7 +92,7 @@ msgstr "" "execução com a GIL desabilitada; caso contrário, importar a extensão " "levantará um aviso e ativará a GIL em tempo de execução." -#: ../../howto/free-threading-extensions.rst:33 +#: ../../howto/free-threading-extensions.rst:41 msgid "" "There are two ways to indicate that an extension module supports running " "with the GIL disabled depending on whether the extension uses multi-phase or " @@ -81,11 +102,11 @@ msgstr "" "com a GIL desabilitada, dependendo se a extensão usa inicialização " "monofásica ou multifásica." -#: ../../howto/free-threading-extensions.rst:38 +#: ../../howto/free-threading-extensions.rst:46 msgid "Multi-Phase Initialization" msgstr "Inicialização multifásica" -#: ../../howto/free-threading-extensions.rst:40 +#: ../../howto/free-threading-extensions.rst:48 msgid "" "Extensions that use multi-phase initialization (i.e., :c:func:" "`PyModuleDef_Init`) should add a :c:data:`Py_mod_gil` slot in the module " @@ -98,11 +119,41 @@ msgstr "" "CPython, você deve proteger o slot com uma verificação de :c:data:" "`PY_VERSION_HEX`." -#: ../../howto/free-threading-extensions.rst:63 +#: ../../howto/free-threading-extensions.rst:55 +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:71 msgid "Single-Phase Initialization" msgstr "Inicialização monofásica" -#: ../../howto/free-threading-extensions.rst:65 +#: ../../howto/free-threading-extensions.rst:73 msgid "" "Extensions that use single-phase initialization (i.e., :c:func:" "`PyModule_Create`) should call :c:func:`PyUnstable_Module_SetGIL` to " @@ -117,15 +168,53 @@ msgstr "" "chamada com ``#ifdef Py_GIL_DISABLED`` para evitar erros de compilação na " "construção regular." -#: ../../howto/free-threading-extensions.rst:93 +#: ../../howto/free-threading-extensions.rst:81 +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:101 msgid "General API Guidelines" msgstr "Diretrizes gerais de API" -#: ../../howto/free-threading-extensions.rst:95 +#: ../../howto/free-threading-extensions.rst:103 msgid "Most of the C API is thread-safe, but there are some exceptions." msgstr "A maior parte da API C é segura para thread, mas há algumas exceções." -#: ../../howto/free-threading-extensions.rst:97 +#: ../../howto/free-threading-extensions.rst:105 msgid "" "**Struct Fields**: Accessing fields in Python C API objects or structs " "directly is not thread-safe if the field may be concurrently modified." @@ -134,7 +223,7 @@ msgstr "" "Python diretamente não é seguro para thread se o campo puder ser modificado " "simultaneamente." -#: ../../howto/free-threading-extensions.rst:99 +#: ../../howto/free-threading-extensions.rst:107 msgid "" "**Macros**: Accessor macros like :c:macro:`PyList_GET_ITEM` and :c:macro:" "`PyList_SET_ITEM` do not perform any error checking or locking. These macros " @@ -145,24 +234,24 @@ msgstr "" "travamento. Essas macros não são seguras para thread se o objeto contêiner " "puder ser modificado simultaneamente." -#: ../../howto/free-threading-extensions.rst:103 +#: ../../howto/free-threading-extensions.rst:111 msgid "" "**Borrowed References**: C API functions that return :term:`borrowed " "references ` may not be thread-safe if the containing " "object is modified concurrently. See the section on :ref:`borrowed " "references ` for more information." msgstr "" -"**Referências emprestadas**: As funções da API C que retornam :term:" +"**Referências emprestadas**: as funções da API C que retornam :term:" "`referências emprestadas ` podem não ser seguras para " "thread se o objeto que as contêm for modificado simultaneamente. Veja a " "seção sobre :ref:`referências emprestadas ` para mais " "informações." -#: ../../howto/free-threading-extensions.rst:110 +#: ../../howto/free-threading-extensions.rst:118 msgid "Container Thread Safety" msgstr "Segurança de threads de contêineres" -#: ../../howto/free-threading-extensions.rst:112 +#: ../../howto/free-threading-extensions.rst:120 msgid "" "Containers like :c:struct:`PyListObject`, :c:struct:`PyDictObject`, and :c:" "struct:`PySetObject` perform internal locking in the free-threaded build. " @@ -174,11 +263,11 @@ msgstr "" "livres. Por exemplo, :c:func:`PyList_Append` irá travar a lista antes de " "anexar um item." -#: ../../howto/free-threading-extensions.rst:120 +#: ../../howto/free-threading-extensions.rst:128 msgid "``PyDict_Next``" msgstr "``PyDict_Next``" -#: ../../howto/free-threading-extensions.rst:122 +#: ../../howto/free-threading-extensions.rst:130 msgid "" "A notable exception is :c:func:`PyDict_Next`, which does not lock the " "dictionary. You should use :c:macro:`Py_BEGIN_CRITICAL_SECTION` to protect " @@ -190,11 +279,29 @@ msgstr "" "dicionário enquanto itera sobre ele se o dicionário puder ser modificado " "simultaneamente::" -#: ../../howto/free-threading-extensions.rst:137 +#: ../../howto/free-threading-extensions.rst:135 +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:145 msgid "Borrowed References" msgstr "Referências emprestadas" -#: ../../howto/free-threading-extensions.rst:141 +#: ../../howto/free-threading-extensions.rst:149 msgid "" "Some C API functions return :term:`borrowed references `. These APIs are not thread-safe if the containing object is " @@ -206,7 +313,7 @@ msgstr "" "contém for modificado simultaneamente. Por exemplo, não é seguro usar :c:" "func:`PyList_GetItem` se a lista puder ser modificada simultaneamente." -#: ../../howto/free-threading-extensions.rst:146 +#: ../../howto/free-threading-extensions.rst:154 msgid "" "The following table lists some borrowed reference APIs and their " "replacements that return :term:`strong references `." @@ -214,81 +321,86 @@ msgstr "" "A tabela a seguir lista algumas APIs de referências emprestadas e suas " "substituições que retornam :term:`referências fortes `." -#: ../../howto/free-threading-extensions.rst:150 +#: ../../howto/free-threading-extensions.rst:158 msgid "Borrowed reference API" msgstr "API de referências emprestadas" -#: ../../howto/free-threading-extensions.rst:150 +#: ../../howto/free-threading-extensions.rst:158 msgid "Strong reference API" msgstr "API de referências fortes" -#: ../../howto/free-threading-extensions.rst:152 +#: ../../howto/free-threading-extensions.rst:160 msgid ":c:func:`PyList_GetItem`" msgstr ":c:func:`PyList_GetItem`" -#: ../../howto/free-threading-extensions.rst:152 +#: ../../howto/free-threading-extensions.rst:160 +#: ../../howto/free-threading-extensions.rst:162 msgid ":c:func:`PyList_GetItemRef`" msgstr ":c:func:`PyList_GetItemRef`" -#: ../../howto/free-threading-extensions.rst:154 +#: ../../howto/free-threading-extensions.rst:162 +msgid ":c:func:`PyList_GET_ITEM`" +msgstr ":c:func:`PyList_GET_ITEM`" + +#: ../../howto/free-threading-extensions.rst:164 msgid ":c:func:`PyDict_GetItem`" msgstr ":c:func:`PyDict_GetItem`" -#: ../../howto/free-threading-extensions.rst:154 -#: ../../howto/free-threading-extensions.rst:156 +#: ../../howto/free-threading-extensions.rst:164 +#: ../../howto/free-threading-extensions.rst:166 msgid ":c:func:`PyDict_GetItemRef`" msgstr ":c:func:`PyDict_GetItemRef`" -#: ../../howto/free-threading-extensions.rst:156 +#: ../../howto/free-threading-extensions.rst:166 msgid ":c:func:`PyDict_GetItemWithError`" msgstr ":c:func:`PyDict_GetItemWithError`" -#: ../../howto/free-threading-extensions.rst:158 +#: ../../howto/free-threading-extensions.rst:168 msgid ":c:func:`PyDict_GetItemString`" msgstr ":c:func:`PyDict_GetItemString`" -#: ../../howto/free-threading-extensions.rst:158 +#: ../../howto/free-threading-extensions.rst:168 msgid ":c:func:`PyDict_GetItemStringRef`" msgstr ":c:func:`PyDict_GetItemStringRef`" -#: ../../howto/free-threading-extensions.rst:160 +#: ../../howto/free-threading-extensions.rst:170 msgid ":c:func:`PyDict_SetDefault`" msgstr ":c:func:`PyDict_SetDefault`" -#: ../../howto/free-threading-extensions.rst:160 +#: ../../howto/free-threading-extensions.rst:170 msgid ":c:func:`PyDict_SetDefaultRef`" msgstr ":c:func:`PyDict_SetDefaultRef`" -#: ../../howto/free-threading-extensions.rst:162 +#: ../../howto/free-threading-extensions.rst:172 msgid ":c:func:`PyDict_Next`" msgstr ":c:func:`PyDict_Next`" -#: ../../howto/free-threading-extensions.rst:162 +#: ../../howto/free-threading-extensions.rst:172 msgid "none (see :ref:`PyDict_Next`)" msgstr "nenhuma (veja :ref:`PyDict_Next`)" -#: ../../howto/free-threading-extensions.rst:164 +#: ../../howto/free-threading-extensions.rst:174 msgid ":c:func:`PyWeakref_GetObject`" msgstr ":c:func:`PyWeakref_GetObject`" -#: ../../howto/free-threading-extensions.rst:164 -#: ../../howto/free-threading-extensions.rst:166 +#: ../../howto/free-threading-extensions.rst:174 +#: ../../howto/free-threading-extensions.rst:176 msgid ":c:func:`PyWeakref_GetRef`" msgstr ":c:func:`PyWeakref_GetRef`" -#: ../../howto/free-threading-extensions.rst:166 +#: ../../howto/free-threading-extensions.rst:176 msgid ":c:func:`PyWeakref_GET_OBJECT`" msgstr ":c:func:`PyWeakref_GET_OBJECT`" -#: ../../howto/free-threading-extensions.rst:168 +#: ../../howto/free-threading-extensions.rst:178 msgid ":c:func:`PyImport_AddModule`" msgstr ":c:func:`PyImport_AddModule`" -#: ../../howto/free-threading-extensions.rst:168 +#: ../../howto/free-threading-extensions.rst:178 msgid ":c:func:`PyImport_AddModuleRef`" msgstr ":c:func:`PyImport_AddModuleRef`" -#: ../../howto/free-threading-extensions.rst:171 +#: ../../howto/free-threading-extensions.rst:181 msgid "" "Not all APIs that return borrowed references are problematic. For example, :" "c:func:`PyTuple_GetItem` is safe because tuples are immutable. Similarly, " @@ -307,7 +419,7 @@ msgstr "" "acessíveis por outros threads), portanto, usar referências emprestadas nesse " "contexto é seguro." -#: ../../howto/free-threading-extensions.rst:179 +#: ../../howto/free-threading-extensions.rst:189 msgid "" "Some of these functions were added in Python 3.13. You can use the " "`pythoncapi-compat `_ package " @@ -318,11 +430,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:197 msgid "Memory Allocation APIs" msgstr "APIs de alocação de memória" -#: ../../howto/free-threading-extensions.rst:187 +#: ../../howto/free-threading-extensions.rst:199 msgid "" "Python's memory management C API provides functions in three different :ref:" "`allocation domains `: \"raw\", \"mem\", and \"object\". " @@ -333,13 +445,13 @@ msgid "" msgstr "" "A API C de gerenciamento de memória do Python fornece funções em três :ref:" "`domínios de alocação ` diferentes: \"raw\", \"mem\" e " -"\"object\". Para segurança de thread, a construção de threads livres requer " +"\"object\". Para segurança de thread, a construção com threads livres requer " "que apenas objetos Python sejam alocados usando o domínio do objeto e que " "todos os objetos Python sejam alocados usando esse domínio. Isso difere das " "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:208 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 +461,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:215 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:217 msgid "" "Python provides a set of functions and macros to manage thread state and the " "GIL, such as:" @@ -361,19 +473,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:220 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:221 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:222 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:224 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 +499,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:230 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 +511,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:237 msgid "Protecting Internal Extension State" msgstr "Protegendo o estado interno das extensões" -#: ../../howto/free-threading-extensions.rst:227 +#: ../../howto/free-threading-extensions.rst:239 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 +525,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:243 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 +535,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:246 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 +547,11 @@ msgstr "" "``thread_local`` ou ``_Thread_local`` para `armazenamento local de thread " "`_." -#: ../../howto/free-threading-extensions.rst:241 +#: ../../howto/free-threading-extensions.rst:253 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:255 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 +560,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:258 msgid "" "`pypa/manylinux `_ supports the free-" "threaded build, with the ``t`` suffix, such as ``python3.13t``." @@ -456,21 +568,21 @@ 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:260 msgid "" "`pypa/cibuildwheel `_ supports the " -"free-threaded build if you set `CIBW_FREE_THREADED_SUPPORT `_." +"free-threaded build if you set `CIBW_ENABLE to cpython-freethreading " +"`_." msgstr "" -"`pypa/cibuildwheel `_ tem suporte à " -"construção com threads livres se você definir `CIBW_FREE_THREADED_SUPPORT " -"`_." +"`pypa/cibuildwheel `_ oferece suporte " +"a construção com threads livres se você definir `CIBW_ENABLE com cpython-" +"freethreading `_." -#: ../../howto/free-threading-extensions.rst:253 +#: ../../howto/free-threading-extensions.rst:265 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:267 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..a4466c772 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..a6caa560a 100644 --- a/howto/functional.po +++ b/howto/functional.po @@ -1,40 +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 -# 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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" @@ -196,10 +188,10 @@ msgid "" "for a second." msgstr "" "Algumas linguagens são muito estritas a respeito da pureza e não tem nem " -"instruções de atribuição como por exemplo ``a=3`` ou ``c = a + b``, mas é " -"difícil evitar todos os efeitos colateirais, como exibir valores na tela ou " -"escrever em um arquivo em disco. Um outro exemplo é a chamada da função :" -"func:`print` ou da função :func:`time.sleep`, nenhuma das quais devolve um " +"instruções de atribuição como, por exemplo, ``a=3`` ou ``c = a + b``, mas é " +"difícil evitar todos os efeitos colaterais, como exibir valores na tela ou " +"escrever em um arquivo em disco. Um outro exemplo é a chamada da função :" +"func:`print` ou da função :func:`time.sleep`, nenhuma das quais retorna um " "valor útil. Ambas são chamadas apenas por conta do efeito colateral de " "mandar algum texto para a tela ou pausar a execução por um segundo." @@ -493,6 +485,20 @@ 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 "" +"for i in iter(obj):\n" +" print(i)\n" +"\n" +"for i in obj:\n" +" print(i)" + #: ../../howto/functional.rst:230 msgid "" "Iterators can be materialized as lists or tuples by using the :func:`list` " @@ -567,6 +573,42 @@ 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 "" +">>> m = {'Jan': 1, 'Fev': 2, 'Mar': 3, 'Abr': 4, 'Mai': 5, 'Jun': 6,\n" +"... 'Jul': 7, 'Ago': 8, 'Set': 9, 'Out': 10, 'Nov': 11, 'Dez': 12}\n" +">>> for key in m:\n" +"... print(key, m[key])\n" +"Jan 1\n" +"Fev 2\n" +"Mar 3\n" +"Abr 4\n" +"Mai 5\n" +"Jun 6\n" +"Jul 7\n" +"Ago 8\n" +"Set 9\n" +"Out 10\n" +"Nov 11\n" +"Dez 12" + #: ../../howto/functional.rst:292 msgid "" "Note that starting with Python 3.7, dictionary iteration order is guaranteed " @@ -608,6 +650,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 +668,28 @@ 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 "" +">>> 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" + #: ../../howto/functional.rst:333 msgid "Generator expressions and list comprehensions" msgstr "Expressões do gerador e compreensões de lista" @@ -648,6 +722,24 @@ 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 "" +">>> line_list = [' line 1\\n', 'line 2 \\n', ' \\n', '']\n" +"\n" +">>> # Expressão geradora -- retorna iterador\n" +">>> stripped_iter = (line.strip() for line in line_list)\n" +"\n" +">>> # Compreensão de lista -- retorna uma lista\n" +">>> stripped_list = [line.strip() for line in line_list]" + #: ../../howto/functional.rst:354 msgid "" "You can select only certain elements by adding an ``\"if\"`` condition::" @@ -655,6 +747,14 @@ 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 "" +">>> stripped_list = [line.strip() for line in line_list\n" +"... if line != \"\"]" + #: ../../howto/functional.rst:359 msgid "" "With a list comprehension, you get back a Python list; ``stripped_list`` is " @@ -684,6 +784,28 @@ 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 "" +"( 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 )" + #: ../../howto/functional.rst:380 msgid "" "Again, for a list comprehension only the outside brackets are different " @@ -715,6 +837,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 "obj_total = sum(obj.count for obj in list_all_objects())" + #: ../../howto/functional.rst:393 msgid "" "The ``for...in`` clauses contain the sequences to be iterated over. The " @@ -739,6 +865,35 @@ 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 "" +"for expr1 in sequence1:\n" +" if not (condition1):\n" +" continue # Ignora este elemento\n" +" for expr2 in sequence2:\n" +" if not (condition2):\n" +" continue # Ignora este elemento\n" +" ...\n" +" for exprN in sequenceN:\n" +" if not (conditionN):\n" +" continue # Ignora este elemento\n" +"\n" +" # Emite o valor da expressão," + #: ../../howto/functional.rst:416 msgid "" "This means that when there are multiple ``for...in`` clauses but no ``if`` " @@ -762,6 +917,18 @@ 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 "" +"# Erro de sintaxe\n" +"[x, y for x in seq1 for y in seq2]\n" +"# Correto\n" +"[(x, y) for x in seq1 for y in seq2]" + #: ../../howto/functional.rst:439 msgid "Generators" msgstr "Geradores" @@ -887,6 +1054,30 @@ 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 "" +"# Um gerador recursivo que gera folhas da árvore em ordem.\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" + #: ../../howto/functional.rst:522 msgid "" "Two other examples in ``test_generators.py`` produce solutions for the N-" @@ -931,6 +1122,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 "val = (yield i)" + #: ../../howto/functional.rst:545 msgid "" "I recommend that you **always** put parentheses around a ``yield`` " @@ -977,6 +1172,28 @@ 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 "" +"def counter(maximum):\n" +" i = 0\n" +" while i < maximum:\n" +" val = (yield i)\n" +" # Se o valor foi fornecido, altera o contador\n" +" if val is not None:\n" +" i = val\n" +" else:\n" +" i += 1" + #: ../../howto/functional.rst:576 msgid "And here's an example of changing the counter:" msgstr "E aqui um exemplo de mudança de contador:" @@ -997,7 +1214,7 @@ msgstr "" msgid "" "In addition to :meth:`~generator.send`, there are two other methods on " "generators:" -msgstr "" +msgstr "Além de :meth:`~generator.send`, há dois outros métodos em geradores:" #: ../../howto/functional.rst:601 msgid "" @@ -1005,10 +1222,13 @@ msgid "" "the generator; the exception is raised by the ``yield`` expression where the " "generator's execution is paused." msgstr "" +":meth:`throw(value) ` é usado para gerar uma exceção dentro " +"do gerador; a exceção é levantada pela expressão ``yield`` onde a execução " +"do gerador é pausada." #: ../../howto/functional.rst:605 msgid "" -":meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the " +":meth:`~generator.close` sends a :exc:`GeneratorExit` exception to the " "generator to terminate the iteration. On receiving this exception, the " "generator's code must either raise :exc:`GeneratorExit` or :exc:" "`StopIteration`; catching the exception and doing anything else is illegal " @@ -1016,6 +1236,12 @@ msgid "" "be called by Python's garbage collector when the generator is garbage-" "collected." msgstr "" +":meth:`~generator.close` envia uma exceção :exc:`GeneratorExit` ao gerador " +"para encerrar a iteração. Ao receber essa exceção, o código do gerador deve " +"levantar :exc:`GeneratorExit` ou :exc:`StopIteration`; capturar a exceção e " +"fazer qualquer outra coisa é ilegal e disparará um :exc:`RuntimeError`. :" +"meth:`~generator.close` também será chamado pelo coletor de lixo do Python " +"quando o gerador for coletado como lixo." #: ../../howto/functional.rst:613 msgid "" @@ -1023,14 +1249,17 @@ msgid "" "suggest using a ``try: ... finally:`` suite instead of catching :exc:" "`GeneratorExit`." msgstr "" +"Se você precisar executar um código de limpeza quando ocorrer um :exc:" +"`GeneratorExit`, sugiro usar um conjunto ``try: ... finally:`` em vez de " +"capturar :exc:`GeneratorExit`." #: ../../howto/functional.rst:616 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 "" @@ -1040,6 +1269,11 @@ msgid "" "can be entered, exited, and resumed at many different points (the ``yield`` " "statements)." msgstr "" +"Geradores também se tornam **corrotinas**, uma forma mais generalizada de " +"subrotinas. As subrotinas são inseridas em um ponto e encerradas em outro (o " +"topo da função e uma instrução ``return``), mas as corrotinas podem ser " +"inseridas, encerradas e retomadas em muitos pontos diferentes (as instruções " +"``yield``)." #: ../../howto/functional.rst:626 msgid "Built-in functions" @@ -1049,22 +1283,28 @@ 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 comumente usadas " +"com iteradores." #: ../../howto/functional.rst:630 msgid "" "Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate " "the features of generator expressions:" msgstr "" +"Duas das funções embutidas do Python, :func:`map` e :func:`filter` duplicam " +"os recursos das expressões geradoras:" #: ../../howto/functional.rst:633 msgid "" ":func:`map(f, iterA, iterB, ...) ` returns an iterator over the sequence" msgstr "" +":func:`map(f, iterA, iterB, ...) ` retorna um iterador sobre a sequência" #: ../../howto/functional.rst:634 msgid "" "``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``." msgstr "" +"``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``." #: ../../howto/functional.rst:644 msgid "You can of course achieve the same effect with a list comprehension." @@ -1079,6 +1319,11 @@ msgid "" "truth value of some condition; for use with :func:`filter`, the predicate " "must take a single value." msgstr "" +":func:`filter(predicate, iter) ` retorna um iterador sobre todos os " +"elementos da sequência que atendem a uma determinada condição, e é " +"similarmente duplicada por compreensões de lista. Um **predicate** é uma " +"função que retorna o valor lógico de alguma condição; para uso com :func:" +"`filter`, o predicado deve receber um único valor." #: ../../howto/functional.rst:659 msgid "This can also be written as a list comprehension:" @@ -1091,12 +1336,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 +1367,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 +1399,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 +1420,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 +1477,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 +1495,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 +1508,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 +1524,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 +1541,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 +1561,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 +1593,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 +1619,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 +1632,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 +1651,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 +1668,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 +1685,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 +1708,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 +1735,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 +1757,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 +1787,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 +1854,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 +1882,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 +1910,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 +1930,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 +1998,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 +2013,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 +2058,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 +2074,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 "" @@ -1672,7 +2221,7 @@ msgstr "" #: ../../howto/functional.rst:1220 msgid "" -"https://www.defmacro.org/ramblings/fp.html: A general introduction to " +"https://defmacro.org/2006/06/19/fp.html: A general introduction to " "functional programming that uses Java examples and has a lengthy historical " "introduction." msgstr "" diff --git a/howto/gdb_helpers.po b/howto/gdb_helpers.po index bd61b0d70..1a53d236c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/index.rst:3 +#: ../../howto/index.rst:5 msgid "Python HOWTOs" msgstr "Python HOWTOs" -#: ../../howto/index.rst:5 +#: ../../howto/index.rst:7 msgid "" "Python HOWTOs are documents that cover a specific topic in-depth. Modeled on " "the Linux Documentation Project's HOWTO collection, this collection is an " "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:41 msgid "General:" msgstr "Geral:" -#: ../../howto/index.rst:39 +#: ../../howto/index.rst:43 +msgid ":ref:`a-conceptual-overview-of-asyncio`" +msgstr ":ref:`a-conceptual-overview-of-asyncio`" + +#: ../../howto/index.rst:44 msgid ":ref:`annotations-howto`" msgstr ":ref:`annotations-howto`" -#: ../../howto/index.rst:40 +#: ../../howto/index.rst:45 msgid ":ref:`argparse-tutorial`" msgstr ":ref:`argparse-tutorial`" -#: ../../howto/index.rst:41 +#: ../../howto/index.rst:46 msgid ":ref:`descriptorhowto`" msgstr ":ref:`descriptorhowto`" -#: ../../howto/index.rst:42 +#: ../../howto/index.rst:47 msgid ":ref:`enum-howto`" msgstr ":ref:`enum-howto`" -#: ../../howto/index.rst:43 +#: ../../howto/index.rst:48 msgid ":ref:`functional-howto`" msgstr ":ref:`functional-howto`" -#: ../../howto/index.rst:44 +#: ../../howto/index.rst:49 msgid ":ref:`ipaddress-howto`" msgstr ":ref:`ipaddress-howto`" -#: ../../howto/index.rst:45 +#: ../../howto/index.rst:50 msgid ":ref:`logging-howto`" msgstr ":ref:`logging-howto`" -#: ../../howto/index.rst:46 +#: ../../howto/index.rst:51 msgid ":ref:`logging-cookbook`" msgstr ":ref:`logging-cookbook`" -#: ../../howto/index.rst:47 +#: ../../howto/index.rst:52 msgid ":ref:`regex-howto`" msgstr ":ref:`regex-howto`" -#: ../../howto/index.rst:48 +#: ../../howto/index.rst:53 msgid ":ref:`sortinghowto`" msgstr ":ref:`sortinghowto`" -#: ../../howto/index.rst:49 +#: ../../howto/index.rst:54 msgid ":ref:`unicode-howto`" msgstr ":ref:`unicode-howto`" -#: ../../howto/index.rst:50 +#: ../../howto/index.rst:55 msgid ":ref:`urllib-howto`" msgstr ":ref:`urllib-howto`" -#: ../../howto/index.rst:52 +#: ../../howto/index.rst:57 msgid "Advanced development:" msgstr "Desenvolvimento avançado:" -#: ../../howto/index.rst:54 +#: ../../howto/index.rst:59 msgid ":ref:`curses-howto`" msgstr ":ref:`curses-howto`" -#: ../../howto/index.rst:55 +#: ../../howto/index.rst:60 +msgid ":ref:`freethreading-python-howto`" +msgstr ":ref:`freethreading-python-howto`" + +#: ../../howto/index.rst:61 msgid ":ref:`freethreading-extensions-howto`" msgstr ":ref:`freethreading-extensions-howto`" -#: ../../howto/index.rst:56 +#: ../../howto/index.rst:62 msgid ":ref:`isolating-extensions-howto`" msgstr ":ref:`isolating-extensions-howto`" -#: ../../howto/index.rst:57 +#: ../../howto/index.rst:63 msgid ":ref:`python_2.3_mro`" msgstr ":ref:`python_2.3_mro`" -#: ../../howto/index.rst:58 +#: ../../howto/index.rst:64 msgid ":ref:`socket-howto`" msgstr ":ref:`socket-howto`" -#: ../../howto/index.rst:59 +#: ../../howto/index.rst:65 msgid ":ref:`timerfd-howto`" msgstr ":ref:`timerfd-howto`" -#: ../../howto/index.rst:60 +#: ../../howto/index.rst:66 msgid ":ref:`cporting-howto`" msgstr ":ref:`cporting-howto`" -#: ../../howto/index.rst:62 +#: ../../howto/index.rst:68 msgid "Debugging and profiling:" msgstr "Depuração e perfilação:" -#: ../../howto/index.rst:64 +#: ../../howto/index.rst:70 msgid ":ref:`gdb`" msgstr ":ref:`gdb`" -#: ../../howto/index.rst:65 +#: ../../howto/index.rst:71 msgid ":ref:`instrumentation`" msgstr ":ref:`instrumentation`" -#: ../../howto/index.rst:66 +#: ../../howto/index.rst:72 msgid ":ref:`perf_profiling`" msgstr ":ref:`perf_profiling`" diff --git a/howto/instrumentation.po b/howto/instrumentation.po index b3fced3ad..ee5a9fbcf 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,150 +571,320 @@ 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 +#: ../../howto/instrumentation.rst:275 msgid "Available static markers" -msgstr "" +msgstr "Marcadores estáticos disponíveis" -#: ../../howto/instrumentation.rst:277 +#: ../../howto/instrumentation.rst:279 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 +#: ../../howto/instrumentation.rst:282 msgid "" "The filename, function name, and line number are provided back to the " "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 +#: ../../howto/instrumentation.rst:286 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 +#: ../../howto/instrumentation.rst:288 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 +#: ../../howto/instrumentation.rst:291 msgid "``$arg3`` : ``int`` line number" -msgstr "" +msgstr "``$arg3`` : número da linha como ``int``" -#: ../../howto/instrumentation.rst:293 +#: ../../howto/instrumentation.rst:295 msgid "" "This marker is the converse of :c:func:`!function__entry`, and indicates " "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 +#: ../../howto/instrumentation.rst:299 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 +#: ../../howto/instrumentation.rst:303 msgid "" "This marker indicates a Python line is about to be executed. It is the " "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 +#: ../../howto/instrumentation.rst:307 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 +#: ../../howto/instrumentation.rst:311 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 +#: ../../howto/instrumentation.rst:316 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 +#: ../../howto/instrumentation.rst:321 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 +#: ../../howto/instrumentation.rst:328 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 +#: ../../howto/instrumentation.rst:337 msgid "" "Fires when :func:`sys.audit` or :c:func:`PySys_Audit` is called. ``arg0`` is " "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 +#: ../../howto/instrumentation.rst:345 msgid "SystemTap Tapsets" -msgstr "" +msgstr "Tapsets de SystemTap" -#: ../../howto/instrumentation.rst:345 +#: ../../howto/instrumentation.rst:347 msgid "" "The higher-level way to use the SystemTap integration is to use a " "\"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 +#: ../../howto/instrumentation.rst:351 msgid "Here is a tapset file, based on a non-shared build of CPython:" msgstr "" - -#: ../../howto/instrumentation.rst:372 +"Aqui está um arquivo tapset, baseado em uma construção não compartilhada do " +"CPython:" + +#: ../../howto/instrumentation.rst:353 +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:374 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 +#: ../../howto/instrumentation.rst:380 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 +#: ../../howto/instrumentation.rst:385 msgid "" "This probe point is the converse of ``python.function.return``, and " "indicates 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 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 +#: ../../howto/instrumentation.rst:392 msgid "Examples" msgstr "Exemplos" -#: ../../howto/instrumentation.rst:391 +#: ../../howto/instrumentation.rst:393 msgid "" "This SystemTap script uses the tapset above to more cleanly implement the " "example given above of tracing the Python function-call hierarchy, without " "needing to directly name the static markers:" msgstr "" - -#: ../../howto/instrumentation.rst:410 +"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:397 +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:412 msgid "" "The following script uses the tapset above to provide a top-like view of all " "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:416 +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..c1fa3bc65 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..29971e4f7 100644 --- a/howto/isolating-extensions.po +++ b/howto/isolating-extensions.po @@ -1,28 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +71,7 @@ msgstr "" #: ../../howto/isolating-extensions.rst:31 msgid "Background" -msgstr "Informações preliminares" +msgstr "Contexto" #: ../../howto/isolating-extensions.rst:33 msgid "" @@ -215,6 +213,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 +278,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 " @@ -326,13 +366,13 @@ msgstr "" msgid "" "If it is necessary to use process-global state, the simplest way to avoid " "issues with multiple interpreters is to explicitly prevent a module from " -"being loaded more than once per process—see `Opt-Out: Limiting to One Module " -"Object per Process`_." +"being loaded more than once per process—see :ref:`isolating-extensions-" +"optout`." msgstr "" "Se for necessário usar estado global para o processo, o jeito mais simples " "de evitar problemas com múltiplos interpretadores é prevenir explicitamente " -"que o módulo seja carregado mais de uma vez por processo—veja `Exclusão " -"voluntária: limitando a um objeto de módulo por processo`_." +"que o módulo seja carregado mais de uma vez por processo — veja :ref:" +"`isolating-extensions-optout`." #: ../../howto/isolating-extensions.rst:175 msgid "Managing Per-Module State" @@ -413,11 +453,11 @@ msgstr "" "`xxlimited `__; há um exemplo de inicialização do módulo no final do arquivo." -#: ../../howto/isolating-extensions.rst:211 +#: ../../howto/isolating-extensions.rst:213 msgid "Opt-Out: Limiting to One Module Object per Process" msgstr "Exclusão voluntária: limitando a um objeto de módulo por processo" -#: ../../howto/isolating-extensions.rst:213 +#: ../../howto/isolating-extensions.rst:215 msgid "" "A non-negative ``PyModuleDef.m_size`` signals that a module supports " "multiple interpreters correctly. If this is not yet the case for your " @@ -429,11 +469,71 @@ 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:220 +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 "" +"// Um sinalizador para todo o processo\n" +"static int loaded = 0;\n" +"\n" +"// Mutex para fornecer segurança para a thread (só necessário para Python de " +"threads livres)\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" +"}" + +#: ../../howto/isolating-extensions.rst:242 +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 "" +"Se a função :c:member:`PyModuleDef.m_clear` do seu módulo for capaz de se " +"preparar para reinicializações futuras, ela deverá limpar o sinalizador " +"``loaded``. Nesse caso, seu módulo não suportará múltiplas instâncias " +"existentes *simultaneamente*, mas suportará, por exemplo, o carregamento " +"após o desligamento do tempo de execução do Python (:c:func:`Py_FinalizeEx`) " +"e a reinicialização (:c:func:`Py_Initialize`)." + +#: ../../howto/isolating-extensions.rst:251 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:253 msgid "" "Accessing the state from module-level functions is straightforward. " "Functions get the module object as their first argument; for extracting the " @@ -443,7 +543,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:257 +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:268 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 +576,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:275 msgid "Heap Types" msgstr "Tipos no heap" -#: ../../howto/isolating-extensions.rst:260 +#: ../../howto/isolating-extensions.rst:277 msgid "" "Traditionally, types defined in C code are *static*; that is, ``static " "PyTypeObject`` structures defined directly in code and initialized using " @@ -468,7 +590,7 @@ msgstr "" "``static PyTypeObject`` definidas diretamente em código e inicializadas " "usando ``PyType_Ready()``." -#: ../../howto/isolating-extensions.rst:264 +#: ../../howto/isolating-extensions.rst:281 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 +603,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:287 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 +620,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:294 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 +634,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:301 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:305 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:307 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 +660,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:316 msgid "" "Watch out for the following two points in particular (but note that this is " "not a comprehensive list):" @@ -546,7 +668,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:319 msgid "" "Unlike static types, heap type objects are mutable by default. Use the :c:" "macro:`Py_TPFLAGS_IMMUTABLETYPE` flag to prevent mutability." @@ -555,7 +677,7 @@ msgstr "" "o sinalizador :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` para impedir a " "mutabilidade." -#: ../../howto/isolating-extensions.rst:304 +#: ../../howto/isolating-extensions.rst:321 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 +687,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:327 msgid "Defining Heap Types" msgstr "Definindo tipos no heap" -#: ../../howto/isolating-extensions.rst:312 +#: ../../howto/isolating-extensions.rst:329 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 +701,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:334 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 +711,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:338 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 +720,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:344 msgid "Garbage-Collection Protocol" msgstr "Protocolo de recolhimento de lixo" -#: ../../howto/isolating-extensions.rst:329 +#: ../../howto/isolating-extensions.rst:346 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 +735,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:351 msgid "" "To avoid memory leaks, instances of heap types must implement the garbage " "collection protocol. That is, heap types should:" @@ -621,11 +743,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:355 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:356 msgid "" "Define a traverse function using ``Py_tp_traverse``, which visits the type " "(e.g. using ``Py_VISIT(Py_TYPE(self))``)." @@ -633,15 +755,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:359 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:363 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 +773,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:369 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:371 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 +787,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:375 +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:383 msgid "" "Unfortunately, :c:data:`Py_Version` was only added in Python 3.11. As a " "replacement, use:" @@ -673,11 +813,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:386 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:387 msgid "" ":py:data:`sys.version_info` (via :c:func:`PySys_GetObject` and :c:func:" "`PyArg_ParseTuple`)." @@ -685,11 +825,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:392 msgid "Delegating ``tp_traverse``" msgstr "Delegando a função ``tp_traverse``" -#: ../../howto/isolating-extensions.rst:377 +#: ../../howto/isolating-extensions.rst:394 msgid "" "If your traverse function delegates to the :c:member:`~PyTypeObject." "tp_traverse` of its base class (or another type), ensure that " @@ -701,16 +841,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:399 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:401 +msgid "base->tp_traverse(self, visit, arg)" +msgstr "base->tp_traverse(self, visit, arg)" + +#: ../../howto/isolating-extensions.rst:403 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:405 +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:413 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 +880,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:418 msgid "Defining ``tp_dealloc``" msgstr "Definindo ``tp_dealloc``" -#: ../../howto/isolating-extensions.rst:403 +#: ../../howto/isolating-extensions.rst:420 msgid "" "If your type has a custom :c:member:`~PyTypeObject.tp_dealloc` function, it " "needs to:" @@ -730,18 +892,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:423 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:424 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:426 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 +911,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:429 +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:438 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 +939,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:444 msgid "Not overriding ``tp_free``" msgstr "Evitar substituir ``tp_free``" -#: ../../howto/isolating-extensions.rst:429 +#: ../../howto/isolating-extensions.rst:446 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 +951,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:452 msgid "Avoiding ``PyObject_New``" msgstr "Evitar ``PyObject_New``" -#: ../../howto/isolating-extensions.rst:437 +#: ../../howto/isolating-extensions.rst:454 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 -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:456 +msgid "If you use :c:func:`PyObject_New` or :c:func:`PyObject_NewVar`:" +msgstr "Se você usa :c:func:`PyObject_New` ou :c:func:`PyObject_NewVar`:" -#: ../../howto/isolating-extensions.rst:441 +#: ../../howto/isolating-extensions.rst:458 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 +973,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:461 +msgid "TYPE *o = typeobj->tp_alloc(typeobj, 0);" +msgstr "TYPE *o = typeobj->tp_alloc(typeobj, 0);" + +#: ../../howto/isolating-extensions.rst:463 msgid "" "Replace ``o = PyObject_NewVar(TYPE, typeobj, size)`` with the same, but use " "size instead of the 0." @@ -799,7 +985,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:466 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 +994,21 @@ msgstr "" "customizado), chame :c:func:`PyObject_GC_New` or :c:func:" "`PyObject_GC_NewVar`::" -#: ../../howto/isolating-extensions.rst:458 +#: ../../howto/isolating-extensions.rst:469 +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:475 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:477 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 +1018,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:481 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 +1026,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:484 +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:491 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:493 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 +1054,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:498 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 +1064,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:502 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 +1075,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:507 msgid "" "The following Python code can illustrate the concept. ``Base." "get_defining_class`` returns ``Base`` even if ``type(self) == Sub``:" @@ -875,7 +1083,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:511 +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:523 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:528 +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:535 msgid "" "Once you have the defining class, call :c:func:`PyType_GetModuleState` to " "get the state of its associated module." @@ -895,19 +1142,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:538 msgid "For example::" msgstr "Por exemplo::" -#: ../../howto/isolating-extensions.rst:549 +#: ../../howto/isolating-extensions.rst:540 +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:566 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:570 msgid "This is new in Python 3.11." msgstr "Adicionado na versão 3.11" -#: ../../howto/isolating-extensions.rst:561 +#: ../../howto/isolating-extensions.rst:578 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 +1220,7 @@ msgstr "" "`PyCMethod`. O mesmo vale para getters e setters definidos com :c:type:" "`PyGetSetDef`." -#: ../../howto/isolating-extensions.rst:568 +#: ../../howto/isolating-extensions.rst:585 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 +1230,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:590 +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:596 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 +1254,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:602 msgid "" "In very exotic cases (inheritance chains spanning multiple modules created " "from the same definition), :c:func:`!PyType_GetModuleByDef` might not return " @@ -956,11 +1267,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:610 msgid "Lifetime of the Module State" msgstr "Tempo de vida do estado do módulo" -#: ../../howto/isolating-extensions.rst:595 +#: ../../howto/isolating-extensions.rst:612 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 +1281,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:616 msgid "" "Usually this is not an issue, because types created with :c:func:" "`PyType_FromModuleAndSpec`, and their instances, hold a reference to the " @@ -984,31 +1295,29 @@ 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:625 msgid "Open Issues" msgstr "Problemas em aberto" -#: ../../howto/isolating-extensions.rst:610 +#: ../../howto/isolating-extensions.rst:627 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:629 msgid "" -"Discussions about improving the situation are best held on the `capi-sig " -"mailing list `__." +"Discussions about improving the situation are best held on the `discuss " +"forum under c-api tag `__." msgstr "" -"O melhor lugar para discussões sobre como melhorar a situação é a `lista de " -"discussão do capi-sig `__." +"Discussões sobre como melhorar a situação são melhor realizadas no `fórum de " +"discussão na tag c-api `__." -#: ../../howto/isolating-extensions.rst:617 +#: ../../howto/isolating-extensions.rst:633 msgid "Per-Class Scope" msgstr "Escopo por classe" -#: ../../howto/isolating-extensions.rst:619 +#: ../../howto/isolating-extensions.rst:635 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 +1329,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:642 msgid "Lossless Conversion to Heap Types" msgstr "Conversão sem perdas para tipos no heap" -#: ../../howto/isolating-extensions.rst:628 +#: ../../howto/isolating-extensions.rst:644 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..2af55f3dd 100644 --- a/howto/logging-cookbook.po +++ b/howto/logging-cookbook.po @@ -1,34 +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: -# Katyanna Moura , 2021 -# Marco Rougeth , 2021 -# Claudio Rogerio Carvalho Filho , 2022 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +42,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 +61,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 principal::" + +#: ../../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 +360,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 +429,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 +444,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 +467,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 +579,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 +630,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 +691,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 +803,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 +842,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 +922,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 +983,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 +1280,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 +1321,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 +1336,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 +1347,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 +1371,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 +1382,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 +1422,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 +1435,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 +1447,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 +1536,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 +1547,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 +1739,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 +1806,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 +1848,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 +1871,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 +2104,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 +2172,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 +2185,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 +2238,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 +2257,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 +2270,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 +2325,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 +2334,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 +2366,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 +2410,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 +2466,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 +2481,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 +2509,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 +2518,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 "logger = logging.getLogger(__name__)" + +#: ../../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 +2532,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 +2542,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 +2550,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 +2572,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 +2990,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 +3003,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 +3245,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 +3253,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 +3262,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 +3301,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 +3317,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 +3413,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 +3537,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 +3563,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 +3592,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 +3607,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 +3615,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 +3623,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 +3642,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 +3662,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 +3673,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 +3718,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 +3737,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 +3811,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 +3820,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 +3832,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 +3912,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 +3971,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 +3984,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 +3993,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 +4005,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 +4141,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 +4217,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 +4244,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 +4315,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 +4353,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 +4392,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 +4477,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 +4669,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 +4679,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 +4694,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 +4959,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 +5045,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 +5068,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 +5138,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 +5200,175 @@ 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:4069 +msgid "How to uniformly handle newlines in logging output" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4071 +msgid "" +"Usually, messages that are logged (say to console or file) consist of a " +"single line of text. However, sometimes there is a need to handle messages " +"with multiple lines - whether because a logging format string contains " +"newlines, or logged data contains newlines. If you want to handle such " +"messages uniformly, so that each line in the logged message appears " +"uniformly formatted as if it was logged separately, you can do this using a " +"handler mixin, as in the following snippet:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4079 +msgid "" +"# Assume this is in a module mymixins.py\n" +"import copy\n" +"\n" +"class MultilineMixin:\n" +" def emit(self, record):\n" +" s = record.getMessage()\n" +" if '\\n' not in s:\n" +" super().emit(record)\n" +" else:\n" +" lines = s.splitlines()\n" +" rec = copy.copy(record)\n" +" rec.args = None\n" +" for line in lines:\n" +" rec.msg = line\n" +" super().emit(rec)" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4097 +msgid "You can use the mixin as in the following script:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4099 +msgid "" +"import logging\n" +"\n" +"from mymixins import MultilineMixin\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"class StreamHandler(MultilineMixin, logging.StreamHandler):\n" +" pass\n" +"\n" +"if __name__ == '__main__':\n" +" logging.basicConfig(level=logging.DEBUG, format='%(asctime)s " +"%(levelname)-9s %(message)s',\n" +" handlers = [StreamHandler()])\n" +" logger.debug('Single line')\n" +" logger.debug('Multiple lines:\\nfool me once ...')\n" +" logger.debug('Another single line')\n" +" logger.debug('Multiple lines:\\n%s', 'fool me ...\\ncan\\'t get fooled " +"again')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4118 +msgid "The script, when run, prints something like:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4120 +msgid "" +"2025-07-02 13:54:47,234 DEBUG Single line\n" +"2025-07-02 13:54:47,234 DEBUG Multiple lines:\n" +"2025-07-02 13:54:47,234 DEBUG fool me once ...\n" +"2025-07-02 13:54:47,234 DEBUG Another single line\n" +"2025-07-02 13:54:47,234 DEBUG Multiple lines:\n" +"2025-07-02 13:54:47,234 DEBUG fool me ...\n" +"2025-07-02 13:54:47,234 DEBUG can't get fooled again" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4130 +msgid "" +"If, on the other hand, you are concerned about `log injection `_, you can use a formatter which " +"escapes newlines, as per the following example:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4134 +msgid "" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"class EscapingFormatter(logging.Formatter):\n" +" def format(self, record):\n" +" s = super().format(record)\n" +" return s.replace('\\n', r'\\n')\n" +"\n" +"if __name__ == '__main__':\n" +" h = logging.StreamHandler()\n" +" h.setFormatter(EscapingFormatter('%(asctime)s %(levelname)-9s " +"%(message)s'))\n" +" logging.basicConfig(level=logging.DEBUG, handlers = [h])\n" +" logger.debug('Single line')\n" +" logger.debug('Multiple lines:\\nfool me once ...')\n" +" logger.debug('Another single line')\n" +" logger.debug('Multiple lines:\\n%s', 'fool me ...\\ncan\\'t get fooled " +"again')" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4154 +msgid "" +"You can, of course, use whatever escaping scheme makes the most sense for " +"you. The script, when run, should produce output like this:" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4157 +msgid "" +"2025-07-09 06:47:33,783 DEBUG Single line\n" +"2025-07-09 06:47:33,783 DEBUG Multiple lines:\\nfool me once ...\n" +"2025-07-09 06:47:33,783 DEBUG Another single line\n" +"2025-07-09 06:47:33,783 DEBUG Multiple lines:\\nfool me ...\\ncan't get " +"fooled again" +msgstr "" + +#: ../../howto/logging-cookbook.rst:4164 +msgid "" +"Escaping behaviour can't be the stdlib default , as it would break backwards " +"compatibility." +msgstr "" + +#: ../../howto/logging-cookbook.rst:4170 msgid "Patterns to avoid" msgstr "" -#: ../../howto/logging-cookbook.rst:4064 +#: ../../howto/logging-cookbook.rst:4172 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 +5376,11 @@ msgid "" "The following sections are in no particular order." msgstr "" -#: ../../howto/logging-cookbook.rst:4070 +#: ../../howto/logging-cookbook.rst:4178 msgid "Opening the same log file multiple times" msgstr "" -#: ../../howto/logging-cookbook.rst:4072 +#: ../../howto/logging-cookbook.rst:4180 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 +5388,32 @@ msgid "" "file multiple times. This could be done accidentally, for example by:" msgstr "" -#: ../../howto/logging-cookbook.rst:4077 +#: ../../howto/logging-cookbook.rst:4185 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:4188 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:4191 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:4195 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:4198 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 +5422,7 @@ msgid "" "different handler instances which happen to point to the same file." msgstr "" -#: ../../howto/logging-cookbook.rst:4096 +#: ../../howto/logging-cookbook.rst:4204 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 +5432,17 @@ msgid "" "being supposedly in place." msgstr "" -#: ../../howto/logging-cookbook.rst:4103 +#: ../../howto/logging-cookbook.rst:4211 msgid "" "Use the techniques outlined in :ref:`multiple-processes` to circumvent such " "issues." msgstr "" -#: ../../howto/logging-cookbook.rst:4107 +#: ../../howto/logging-cookbook.rst:4215 msgid "Using loggers as attributes in a class or passing them as parameters" msgstr "" -#: ../../howto/logging-cookbook.rst:4109 +#: ../../howto/logging-cookbook.rst:4217 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 +5453,13 @@ msgid "" "module (and not the class) is the unit of software decomposition." msgstr "" -#: ../../howto/logging-cookbook.rst:4118 +#: ../../howto/logging-cookbook.rst:4226 msgid "" "Adding handlers other than :class:`~logging.NullHandler` to a logger in a " "library" msgstr "" -#: ../../howto/logging-cookbook.rst:4120 +#: ../../howto/logging-cookbook.rst:4228 msgid "" "Configuring logging by adding handlers, formatters and filters is the " "responsibility of the application developer, not the library developer. If " @@ -2071,11 +5467,11 @@ msgid "" "your loggers other than a :class:`~logging.NullHandler` instance." msgstr "" -#: ../../howto/logging-cookbook.rst:4126 +#: ../../howto/logging-cookbook.rst:4234 msgid "Creating a lot of loggers" msgstr "" -#: ../../howto/logging-cookbook.rst:4128 +#: ../../howto/logging-cookbook.rst:4236 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 +5482,38 @@ msgid "" "occasionally slightly more fine-grained than that)." msgstr "" -#: ../../howto/logging-cookbook.rst:4139 +#: ../../howto/logging-cookbook.rst:4247 msgid "Other resources" msgstr "Outros recursos" -#: ../../howto/logging-cookbook.rst:4143 +#: ../../howto/logging-cookbook.rst:4251 msgid "Module :mod:`logging`" msgstr "Módulo :mod:`logging`" -#: ../../howto/logging-cookbook.rst:4144 +#: ../../howto/logging-cookbook.rst:4252 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:4254 msgid "Module :mod:`logging.config`" msgstr "Módulo :mod:`logging.config`" -#: ../../howto/logging-cookbook.rst:4147 +#: ../../howto/logging-cookbook.rst:4255 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:4257 msgid "Module :mod:`logging.handlers`" msgstr "Módulo :mod:`logging.handlers`" -#: ../../howto/logging-cookbook.rst:4150 +#: ../../howto/logging-cookbook.rst:4258 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:4260 msgid ":ref:`Basic Tutorial `" msgstr ":ref:`Tutorial básico `" -#: ../../howto/logging-cookbook.rst:4154 +#: ../../howto/logging-cookbook.rst:4262 msgid ":ref:`Advanced Tutorial `" msgstr ":ref:`Tutorial avançado `" diff --git a/howto/logging.po b/howto/logging.po index b6e164ec0..a1cb6d355 100644 --- a/howto/logging.po +++ b/howto/logging.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: -# 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +41,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 livro de receitas de logging, por favor veja :" +"ref:`tutorial-ref-links`." #: ../../howto/logging.rst:17 msgid "Basic Logging Tutorial" @@ -66,12 +60,12 @@ msgid "" "the *level* or *severity*." msgstr "" "Logging é uma maneira de rastrear eventos que acontecem quando algum " -"software executa. O desenvolvedor de software adiciona chamadas de logging " -"no código para indicar que determinado evento ocorreu. Um evento é descrito " -"por uma mensagem descritiva que pode opcionalmente conter o dado de uma " -"variável (ex.: dado que é potencialmente diferente pra cada ocorrência do " -"evento). Eventos também tem um peso que o desenvolvedor atribui para o " -"evento; o peso pode também ser chamada de *níveis* ou *severidade*." +"software é executado. O desenvolvedor de software adiciona chamadas de " +"logging no código para indicar que determinado evento ocorreu. Um evento é " +"definido por uma mensagem descritiva que pode opcionalmente conter o valor " +"de uma variável (ex.: um dado que é potencialmente diferente pra cada " +"ocorrência do evento). Eventos também possuem importâncias atribuídas pelo " +"desenvolvedor; esta importância pode ser chamada de *nível* ou *severidade*." #: ../../howto/logging.rst:28 msgid "When to use logging" @@ -86,10 +80,16 @@ 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 instanciar loggers com ``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 a necessidade ou não de usar logging, e escolher o método " +"adequado, consulte a tabela abaixo. Ela indica, para cada conjunto de " +"tarefas comuns, a melhor ferramenta a ser usada." #: ../../howto/logging.rst:38 msgid "Task you want to perform" -msgstr "Tarefa que você quer performar" +msgstr "Tarefa que você deseja executar" #: ../../howto/logging.rst:38 msgid "The best tool for the task" @@ -99,8 +99,8 @@ msgstr "A melhor ferramenta para a tarefa" msgid "" "Display console output for ordinary usage of a command line script or program" msgstr "" -"Exibir saída do console para uso ordinário de um script de linha de comando " -"ou programa." +"Exibir uma mensagem na saída do console para uso ordinário de um script de " +"linha de comando (CLI) ou programa." #: ../../howto/logging.rst:40 msgid ":func:`print`" @@ -111,36 +111,45 @@ msgid "" "Report events that occur during normal operation of a program (e.g. for " "status monitoring or fault investigation)" msgstr "" -"Relata eventos que podem ocorrer durante a operação normal de um programa " -"(ex: para monitoramento do status ou investigação de falha)" +"Expor eventos que possam ocorrer durante a operação normal de um programa " +"(por exemplo, para monitorar o estado atual de execução ou poder investigar " +"falhas)" #: ../../howto/logging.rst:44 msgid "" "A logger's :meth:`~Logger.info` (or :meth:`~Logger.debug` method for very " "detailed output for diagnostic purposes)" msgstr "" +"Utilize o método :meth:`~Logger.info` de um logger (ou o método :meth:" +"`~Logger.debug`, no caso de mensagens mais detalhadas para diagnóstico e " +"investigação de erros)" #: ../../howto/logging.rst:49 msgid "Issue a warning regarding a particular runtime event" -msgstr "Emite um aviso sobre um evento de tempo de execução específico" +msgstr "" +"Emitir um aviso sobre um evento que ocorre em um tempo de execução específico" #: ../../howto/logging.rst:49 msgid "" ":func:`warnings.warn` in library code if the issue is avoidable and the " "client application should be modified to eliminate the warning" msgstr "" -":func:`warnings.warn` na biblioteca de código se o problema é evitável e a " -"aplicação cliente deve ser modificada para eliminar o alerta." +"Utilize a função :func:`warnings.warn` da biblioteca padrão se o problema " +"for evitável, e caso a aplicação deva ser modificada pelo usuário para " +"eliminar o alerta." #: ../../howto/logging.rst:54 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 "" +"Utilize o método :meth:`~Logger.warning` de um logger, caso não haja nada " +"que o usuário possa fazer na aplicação, mas o evento ainda deva ser " +"registrado" #: ../../howto/logging.rst:60 msgid "Report an error regarding a particular runtime event" -msgstr "Relata um erro sobre um evento de tempo de execução específico" +msgstr "Expor um erro sobre um evento em um tempo de execução específico" #: ../../howto/logging.rst:60 msgid "Raise an exception" @@ -151,8 +160,8 @@ msgid "" "Report suppression of an error without raising an exception (e.g. error " "handler in a long-running server process)" msgstr "" -"Relatar supressão de um erro sem levantar uma exceção (ex: manipulador de " -"erros em um processo de servidor em longa execução)" +"Expor a supressão de um erro sem levantar uma exceção (por exemplo, ao " +"utilizar um tratador de erro em um processo de longa execução)" #: ../../howto/logging.rst:63 msgid "" @@ -160,6 +169,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 +179,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 +191,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``" @@ -184,10 +199,10 @@ msgstr "``DEBUG``" msgid "" "Detailed information, typically of interest only when diagnosing problems." msgstr "" -"Informação detalhada, tipicamente de interesse apenas quando diagnosticando " +"Informação detalhada, tipicamente utilizáveis apenas para diagnosticar " "problemas." -#: ../../howto/logging.rst:82 ../../howto/logging.rst:879 +#: ../../howto/logging.rst:82 ../../howto/logging.rst:883 msgid "``INFO``" msgstr "``INFO``" @@ -195,7 +210,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``" @@ -205,11 +220,11 @@ msgid "" "problem in the near future (e.g. 'disk space low'). The software is still " "working as expected." msgstr "" -"Uma indicação que algo inesperado aconteceu, ou um indicativo que algum " -"problema em um futuro próximo (ex.: 'pouco espaço em disco'). O software " -"está ainda funcionando como esperado." +"Uma indicação que algo inesperado aconteceu, ou um indicativo de que poderá " +"haver algum problema em um futuro próximo (por exemplo: '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 +236,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 +253,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,9 +275,23 @@ 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('Cuidado!') # exibirá uma mensagem no console\n" +"logging.info('Eu te avisei') # não exibirá 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á:" +msgstr "Se você colocar essas linhas no script e executá-lo, você verá:" + +#: ../../howto/logging.rst:118 +msgid "WARNING:root:Watch out!" +msgstr "WARNING:root:Cuidado!" #: ../../howto/logging.rst:122 msgid "" @@ -269,6 +301,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 "" +"no console. A mensagem ``INFO`` não aparece porque o nível padrão de logging " +"é ``WARNING`` . A mensagem exibida inclui a indicação do nível e a descrição " +"do evento fornecido na chamada de logging. Ou seja, 'Cuidado!'. A saída 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 +318,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 +337,31 @@ 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. Teste o código a seguir em um " +"interpretador Python recém-iniciado. Não continue a partir da sessão usada " +"para o código anterior." + +#: ../../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 "" +"import logging\n" +"logger = logging.getLogger(__name__)\n" +"logging.basicConfig(filename='exemplo.log', encoding='utf-8', level=logging." +"DEBUG)\n" +"logger.debug('Esta mensagem aparecerá no arquivo de log')\n" +"logger.info('Esta também')\n" +"logger.warning('E também essa')\n" +"logger.error('Além de palavras com caracteres não-ASCII, como Øresund e " +"Malmö')" #: ../../howto/logging.rst:151 msgid "" @@ -302,6 +371,12 @@ msgid "" "passed, which determines how encoding errors are handled. For available " "values and the default, see the documentation for :func:`open`." msgstr "" +"O argumento de codificação *encoding* foi adicionado. Em versões anteriores " +"do Python, a codificação utilizada por padrão seria definida em :func:" +"`open`. Embora não seja mostrado no exemplo acima, um argumento de *erro* " +"pode ser utilizado, o que determina como o codificação de erros são " +"tratadas. Para saber mais sobre essas possibilidades, consulte a " +"documentação de :func:`open`." #: ../../howto/logging.rst:158 msgid "" @@ -311,30 +386,51 @@ 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 "" +"DEBUG:__main__:Esta mensagem aparecerá no arquivo de log\n" +"INFO:__main__:Esta também\n" +"WARNING:__main__:E também essa\n" +"ERROR:__main__:Além de palavras com caracteres não-ASCII, como Øresund e " +"Malmö" + #: ../../howto/logging.rst:168 msgid "" "This example also shows how you can set the logging level which acts as the " "threshold for tracking. In this case, because we set the threshold to " "``DEBUG``, all of the messages were printed." msgstr "" -"Este exemplo também mostra como você pode configurar o nível do logging que " -"age como um limiar para o rastreamento. Neste caso, por causa que definimos " -"o limiar como ``DEBUG``, todas as mensagens foram exibidas." +"Este exemplo também mostra como você pode configurar o nível do logging , " +"que funcionará como um limite para o rastreamento. Neste caso, como " +"definimos o nível limite como ``DEBUG``, todas as mensagens foram exibidas." #: ../../howto/logging.rst:172 msgid "" "If you want to set the logging level from a command-line option such as:" msgstr "" -"Se você quer definir o nível de logging a partir de uma opção da linha de " -"comando como:" +"Você também pode definir o nível de logging a partir de um parâmetro pela " +"linha de comando (CLI):" + +#: ../../howto/logging.rst:174 +msgid "--log=INFO" +msgstr "--log=INFO" #: ../../howto/logging.rst:178 msgid "" "and you have the value of the parameter passed for ``--log`` in some " "variable *loglevel*, you can use::" msgstr "" -"e você tem o valor do parâmetro passado pelo ``--log`` em alguma variável " -"*loglevel*, você pode usar::" +"e se você quiser obter o valor do parâmetro ``--log`` em algum ponto do " +"código, você pode usar:" + +#: ../../howto/logging.rst:181 +msgid "getattr(logging, loglevel.upper())" +msgstr "getattr(logging, loglevel.upper())" #: ../../howto/logging.rst:183 msgid "" @@ -342,9 +438,29 @@ msgid "" "argument. You may want to error check any user input value, perhaps as in " "the following example::" msgstr "" -"para obter o valor que você passará para a :func:`basicConfig` via o *level* " -"argumento. Você pode querer verificar qualquer erros introduzidos pelo " -"usuário, talvez como no exemplo a seguir::" +"para obter o valor que você passará para a :func:`basicConfig` pelo " +"argumento de nível *level*. Isso pode ser útil para verificar erros " +"introduzidos pelo usuário, 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 "" +"# presumindo que a variável loglevel está atrelada ao valor da string " +"obtida\n" +"# pelo argumento de linha de comando; Converter para caixa alta permite ao " +"usuário\n" +"# declarar tanto --log=DEBUG quanto--log=debug\n" +"nivel_numerico = getattr(logging, loglevel.upper(), None)\n" +"if not isinstance(nivel_numerico , int):\n" +" raise ValueError('Nível de log invalido: %s' % loglevel)\n" +"logging.basicConfig(level=nivel_numerico, ...)" #: ../../howto/logging.rst:195 msgid "" @@ -352,6 +468,10 @@ msgid "" "methods such as :meth:`~Logger.debug`, :meth:`~Logger.info`, etc. Otherwise, " "that logging event may not be handled in the desired manner." msgstr "" +"A chamada para :func:`basicConfig` deve vir *antes* de qualquer chamada para " +"métodos de um logger, como :meth:`~Logger.debug`, :meth:`~Logger.info`, etc. " +"Caso contrário, o logging deste evento pode não ser tratado da forma " +"desejada." #: ../../howto/logging.rst:199 msgid "" @@ -361,10 +481,18 @@ msgid "" "*filemode* argument, by changing the call in the above example to::" msgstr "" "Se você executar o script acima diversas vezes, as mensagens das sucessivas " -"execuções serão acrescentadas ao arquivo *example.log*. Se você quer que " +"execuções serão acrescentadas ao arquivo *exemplo.log*. Se você quiser que " "cada execução seja iniciada novamente, não guardando as mensagens das " -"execuções anteriores, você pode especificar o *filemode* argumento, mudando " -"a chamada no exemplo acima::" +"execuções anteriores, você pode definir o argumento *filemode*, mudando a " +"chamada no exemplo acima para:" + +#: ../../howto/logging.rst:204 +msgid "" +"logging.basicConfig(filename='example.log', filemode='w', level=logging." +"DEBUG)" +msgstr "" +"logging.basicConfig(filename='exemplo.log', filemode='w', level=logging." +"DEBUG)" #: ../../howto/logging.rst:206 msgid "" @@ -372,12 +500,12 @@ msgid "" "appended to, so the messages from earlier runs are lost." msgstr "" "A saída será a mesma de antes, mas o arquivo de log não será mais " -"incrementado, desta forma as mensagens de execuções anteriores serão " +"incrementado. Desta forma, as mensagens de execuções anteriores serão " "perdidas." #: ../../howto/logging.rst:211 msgid "Logging variable data" -msgstr "Logging dados de uma variável" +msgstr "Logging de variáveis dinâmicas" #: ../../howto/logging.rst:213 msgid "" @@ -387,10 +515,22 @@ 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 "" +"import logging\n" +"logging.warning('%s onde você %s', 'Olhe', 'anda!')" + #: ../../howto/logging.rst:219 msgid "will display:" msgstr "exibirá:" +#: ../../howto/logging.rst:221 +msgid "WARNING:root:Look before you leap!" +msgstr "WARNING:root:Olhe onde você anda!" + #: ../../howto/logging.rst:225 msgid "" "As you can see, merging of variable data into the event description message " @@ -401,12 +541,11 @@ msgid "" "tutorial: see :ref:`formatting-styles` for more information." msgstr "" "Como você pode ver, para combinar uma variável de dados na mensagem " -"descritiva do evento usamos o velho, %-s estilo de formatação de string. " -"Isto é usado para garantir compatibilidade com as versões anteriores: o " -"pacote logging pré-data novas opções de formatação como :meth:`str.format` " -"e :class:`string.Template`. Estas novas opções de formatação são suportadas, " -"mas explorá-las esta fora do escopo deste tutorial: veja :ref:`formatting-" -"styles`  para mais informações." +"descritiva do evento usamos o velho operador %, formatador de strings. Isto " +"é usado para garantir compatibilidade com as versões anteriores: os pacotes " +"logging mais recentes contam com opções de formatação como :meth:`str." +"format` e :class:`string.Template`. Mas explorar estes métodos está fora do " +"escopo deste tutorial. Veja :ref:`formatting-styles` para mais informações." #: ../../howto/logging.rst:234 msgid "Changing the format of displayed messages" @@ -420,10 +559,36 @@ 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 "" +"import logging\n" +"logging.basicConfig(format='%(levelname)s:%(message)s', level=logging." +"DEBUG)\n" +"logging.debug('Esta mensagem aparecerá no console')\n" +"logging.info('Esta também')\n" +"logging.warning('E também essa')" + #: ../../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 "" +"DEBUG:Esta mensagem aparecerá no console\n" +"INFO:Esta também\n" +"WARNING:E também essa" + #: ../../howto/logging.rst:253 msgid "" "Notice that the 'root' which appeared in earlier examples has disappeared. " @@ -449,27 +614,57 @@ msgid "" "To display the date and time of an event, you would place '%(asctime)s' in " "your format string::" msgstr "" -"Para exibir a data e hora de um evento, você pode colocar '%(asctime)s' no " -"seu formato string::" +"Para exibir a data e hora de um evento, você pode colocar `%(asctime)s` na " +"sua string de formato:" + +#: ../../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 "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s')\n" +"logging.warning('foi quando este evento foi registrado.')" #: ../../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 "2010-12-12 11:41:42,612 foi quando este evento foi registrado." + #: ../../howto/logging.rst:277 msgid "" "The default format for date/time display (shown above) is like ISO8601 or :" "rfc:`3339`. If you need more control over the formatting of the date/time, " "provide a *datefmt* argument to ``basicConfig``, as in this example::" msgstr "" -"O formato padrão para data/hora (mostrado abaixo) é como a ISO8601 ou :rfc:" -"`3339`. Se você precisa de mais controle sobre a formatação de data/hora, " -"informe o *datefmt* argumento para ``basicConfig``, como neste exemplo::" +"O formato padrão para data/hora (mostrado abaixo) é a ISO8601 ou a :rfc:" +"`3339`. Se você precisar de mais controle sobre a formatação de data/hora, " +"defina o argumento *datefmt* na função ``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 "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:" +"%M:%S %p')\n" +"logging.warning('foi quando este evento foi registrado.')" #: ../../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 "12/12/2010 11:46:36 AM foi quando este evento foi registrado." + #: ../../howto/logging.rst:291 msgid "" "The format of the *datefmt* argument is the same as supported by :func:`time." @@ -500,10 +695,15 @@ msgstr "" msgid "" "If your logging needs are simple, then use the above examples to incorporate " "logging into your own scripts, and if you run into problems or don't " -"understand something, please post a question on the comp.lang.python Usenet " -"group (available at https://groups.google.com/g/comp.lang.python) and you " +"understand something, please post a question in the Help category of the " +"`Python discussion forum `_ and you " "should receive help before too long." msgstr "" +"Se as suas necessidades de logging forem simples, use os exemplos acima para " +"incorporar o registro em seus próprios scripts e, se tiver problemas ou não " +"entender alguma coisa, publique uma pergunta na categoria Help do fórum de " +"discussão `Python `_. Você deverá " +"receber ajuda em breve." #: ../../howto/logging.rst:310 msgid "" @@ -525,7 +725,7 @@ msgid "" "of components: loggers, handlers, filters, and formatters." msgstr "" "A biblioteca de logging tem uma abordagem modular e oferece algumas " -"categorias de componentes: loggers, handlers, filters, e formatters." +"categorias de componentes: loggers, manipuladores, filtros, e formatadores." #: ../../howto/logging.rst:323 msgid "Loggers expose the interface that application code directly uses." @@ -557,8 +757,8 @@ msgid "" "Log event information is passed between loggers, handlers, filters and " "formatters in a :class:`LogRecord` instance." msgstr "" -"Uma informação de um evento de log é passada entre loggers, handlers, " -"filters e formatters em uma instância de uma :class:`LogRecord`" +"Um evento, quando registrado, passa por loggers, manipuladores, filtros e " +"formatadores através de uma instância de :class:`LogRecord`" #: ../../howto/logging.rst:333 msgid "" @@ -570,30 +770,34 @@ msgid "" "want, and indicate the area of an application in which a logged message " "originates." msgstr "" -"Logging é executada chamando métodos nas instâncias da :class:`Logger` " -"classe, também chamado de :dfn:`loggers`. Cada instância tem um nome, e eles " -"são conceitualmente organizados em uma hierarquia de espaço de nomes usando " -"pontos como separadores. Por exemplo, um logger nomeado com 'scan' é o pai " -"do logger 'scan.text', 'scan.html' e 'scan.pdf'. Você pode nomear o logger " -"do jeito que preferir, e indicar a área de uma aplicação em que uma mensagem " -"de log origina." +"Para executar uma ação de logging, é necessário criar instâncias da classe :" +"class:`Logger` (também chamadas de :dfn:`loggers`), e invocar seus métodos. " +"Cada instância tem um nome, e elas são conceitualmente organizadas em uma " +"hierarquia de espaço de nomes utilizando pontos como separadores. Por " +"exemplo, um logger nomeado como 'leitor' é o pai do logger 'leitor.texto', " +"'leitor.html' e 'leitor.pdf'. Você pode nomear o logger do jeito que " +"preferir, e indicar o trecho da aplicação que origina a mensagem de log." #: ../../howto/logging.rst:340 msgid "" "A good convention to use when naming loggers is to use a module-level " "logger, in each module which uses logging, named as follows::" 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::" +"Uma boa prática ao nomear loggers é criar, em cada módulo que usa logging, " +"um logger definido no mesmo nível do módulo. Como no exemplo abaixo:" + +#: ../../howto/logging.rst:343 +msgid "logger = logging.getLogger(__name__)" +msgstr "logger = logging.getLogger(__name__)" #: ../../howto/logging.rst:345 msgid "" "This means that logger names track the package/module hierarchy, and it's " "intuitively obvious where events are logged just from the logger name." msgstr "" -"Isto significa que o nome de um logger rastreia a hierarquia do pacote/" -"módulo, e isto é obviamente intuitivo onde os eventos estão sendo " -"registrados apenas pelo nome do logger." +"Isso significa que os nomes dos loggers acompanham a hierarquia de pacotes e " +"módulos, tornando intuitivo saber de onde os eventos foram registrados " +"apenas olhando o nome do logger." #: ../../howto/logging.rst:348 msgid "" @@ -603,6 +807,12 @@ msgid "" "the root logger. The functions and the methods have the same signatures. The " "root logger's name is printed as 'root' in the logged output." msgstr "" +"O início da hierarquia de loggers é chamado de logger raiz. É ele que é " +"usado pelas funções :func:`debug`, :func:`info`, :func:`warning`, :func:" +"`error` e :func:`critical`, que apenas chamam o método de mesmo nome dentro " +"do logger raiz. Essas funções, e seus métodos correspondentes, têm a mesma " +"assinatura (mesmos parâmetros aceitos). Na saída do log, o nome do logger " +"raiz aparece como 'root'." #: ../../howto/logging.rst:354 msgid "" @@ -614,6 +824,14 @@ msgid "" "destination class if you have special requirements not met by any of the " "built-in handler classes." msgstr "" +"É possível registrar mensagens de log em diferentes destinos. O pacote já " +"traz suporte para enviar logs para arquivos, URLs via HTTP GET/POST, e-mails " +"via SMTP, soquetes genéricos, filas ou mecanismos de log específicos do " +"sistema operacional, como o syslog no Unix/Linux ou o Event Log do Windows " +"NT. Esses destinos são gerenciados por classes chamadas manipuladores. Se " +"precisar de um destino especial que não seja atendido pelos manipuladores " +"embutidos, você poderá criar sua própria classe manipuladora para destinar " +"corretamente o log." #: ../../howto/logging.rst:361 msgid "" @@ -626,33 +844,50 @@ msgid "" "displayed message before delegating to the root logger to do the actual " "message output." msgstr "" +"Por padrão, nenhum destino é definido para nenhuma mensagem de registro. É " +"possível especificar um destino (como console, ou arquivo) usando :func:" +"`basicConfig`, como nos exemplos do tutorial. Se você chamar as funções :" +"func:`debug` , :func:`info`, :func:`warning`, :func:`error` e :func:" +"`critical`, elas verificarão se o destino está definido; e, caso não esteja, " +"elas definirão o console como o destino (``sys.stderr``) e definirão o " +"formato utilizando um formato padrão. Só então, enviarão a mensagem ao " +"logger raiz, para que seja registrada na saída." #: ../../howto/logging.rst:369 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 "severity:logger name:message" + #: ../../howto/logging.rst:375 msgid "" "You can change this by passing a format string to :func:`basicConfig` with " "the *format* keyword argument. For all options regarding how a format string " "is constructed, see :ref:`formatter-objects`." msgstr "" +"Você pode alterar isso passando uma string de formato para :func:" +"`basicConfig`, através do argumento nomeado *format*. Para sobre como uma " +"string de formato é construída, consulte :ref:`formatter-objects`." #: ../../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 manipuladores é 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 " @@ -661,20 +896,26 @@ msgid "" "Third, logger objects pass along relevant log messages to all interested log " "handlers." msgstr "" +"Objetos :class:`Logger` têm três funções principais. Primeiro, eles expõem " +"vários métodos para que o código da aplicação possa registrar mensagens " +"durante a execução. Segundo, eles decidem quais mensagens de log devem ser " +"processadas, com base no nível de severidade (é o filtro padrão) ou em " +"objetos filtro. Terceiro, eles encaminham as mensagens de log relevantes " +"para todos os manipuladores de log interessados." -#: ../../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." msgstr "" -"Os métodos mais usados em objetos logger se enquadram em duas categorias: " -"configuração e envio de mensagem." +"Os métodos mais utilizados 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 " @@ -682,33 +923,47 @@ msgid "" "INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL " "messages and will ignore DEBUG messages." msgstr "" +":meth:`Logger.setLevel` especifica o nível mínimo de severidade que um " +"logger vai lidar. O nível DEBUG é o mais baixo, e o CRITICAL é o mais alto " +"entre os níveis padrão. Por exemplo, se o nível do logger for INFO, ele vai " +"processar apenas mensagens de nível INFO, WARNING, ERROR e CRITICAL, e vai " +"ignorar mensagens DEBUG." -#: ../../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 "" +":meth:`Logger.addHandler` e :meth:`Logger.removeHandler` adicionam e removem " +"objetos manipuladores do objeto logger. Manipuladores serão aprofundados em :" +"ref:`handler-basic`." -#: ../../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 "" +":meth:`Logger.addFilter` e :meth:`Logger.removeFilter` adicionam e removem " +"objetos filtros do objeto logger. Filtros serão aprofundados em :ref:" +"`filter`." -#: ../../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. " +"Consulte os últimos dois paragrafos nessa mesma 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 " @@ -720,23 +975,40 @@ msgid "" "about a keyword of ``exc_info`` and use it to determine whether to log " "exception information." msgstr "" +":meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, :meth:" +"`Logger.error` e :meth:`Logger.critical` criam logs com uma mensagem em um " +"nível correspondente ao respectivo nome do método. A mensagem é uma string " +"de formato, que pode conter a sintaxe padrão de substituições como ``%s``, " +"``%d`` e ``%f``. O restante dos argumentos são uma lista de objetos que " +"correspondem aos campos de substituição da mensagem. No caso do parâmetro " +"``**kwargs``, os métodos de logging cuidam apenas da chave ``exc_info``. É " +"essa chave que eles usam para decidir se devem ou não registrar os detalhes " +"de uma exceção." -#: ../../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 "" +":meth:`Logger.exception` cria uma mensagem de log parecida com :meth:`Logger." +"error`. A diferença é que, além da mensagem, :meth:`Logger.exception` também " +"registra o stack trace (situação da pilha de execução). Chame este método " +"apenas a partir de um manipulador de exceção." -#: ../../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 " "convenience methods listed above, but this is how to log at custom log " "levels." msgstr "" +":meth:`Logger.log` recebe o nível de log como um argumento explícito. Isso " +"torna o registro de mensagens um pouco mais verboso do que usar os métodos " +"prontos para cada nível, com os métodos listados anteriormente, mas é uma " +"forma de registrar mensagens em níveis de log personalizados." -#: ../../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-" @@ -747,8 +1019,17 @@ msgid "" "loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all " "descendants of ``foo``." msgstr "" +":func:`getLogger` retorna uma referência para uma instância de um logger com " +"o nome especificado, caso informado, ou para o logger raiz (caso nenhum nome " +"seja passado). Os nomes seguem uma estrutura hierárquica separada por " +"pontos. Chamadas repetidas a :func:`getLogger` com o mesmo nome retornam " +"sempre uma referência para a mesma instância do objeto logger. Loggers que " +"aparecem mais embaixo na hierarquia são filhos dos loggers que estão mais " +"acima nessa lista. Por exemplo, dado um logger com nome ``foo``, loggers com " +"os nomes ``foo.bar``, ``foo.bar.baz`` e ``foo.bam`` serão todos descendentes " +"de ``foo``." -#: ../../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 " @@ -759,8 +1040,16 @@ msgid "" "the logger is used to determine whether the event is passed to the logger's " "handlers." msgstr "" +"Loggers têm o conceito de nível efetivo. Se um logger não tiver um nível " +"definido explicitamente, ele herdará o nível do seu logger pai. Caso o pai " +"também não tenha um nível definido, o processo continua subindo na " +"hierarquia, examinando cada ancestral, até encontrar um logger com nível " +"configurado. O logger raiz sempre terá um nível explícito configurado (por " +"padrão, ``WARNING``). Ao decidir se um evento será processado, o logger usa " +"o seu nível efetivo para determinar se o evento deve ser repassado para os " +"manipuladores responsáveis." -#: ../../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 " @@ -769,12 +1058,18 @@ msgid "" "needed. (You can, however, turn off propagation by setting the *propagate* " "attribute of a logger to ``False``.)" msgstr "" +"Loggers filhos propagam suas mensagens para os manipuladores associados aos " +"seus loggers ancestrais. Por causa disso, não é necessário definir e " +"configurar manipuladores para todos os loggers usados em uma aplicação. " +"Basta configurar os manipuladores em um logger de nível superior, e criar " +"loggers filhos conforme a necessidade. No entanto, é possível desativar essa " +"propagação definindo o atributo *propagate* do logger como ``False``." -#: ../../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 " @@ -786,23 +1081,40 @@ msgid "" "individual handlers where each handler is responsible for sending messages " "of a specific severity to a specific location." msgstr "" +"Objetos :class:`~logging.Handler` são responsáveis por enviar as mensagens " +"de log apropriadas (com base na severidade de cada mensagem) para o destino " +"especificado do manipulador. Objetos :class:`Logger` podem adicionar um ou " +"mais manipuladores a si mesmos usando o método :meth:`~Logger.addHandler`. " +"Em um cenário hipotético, uma aplicação pode querer \"enviar todas as " +"mensagens de log para um arquivo\", \"enviar apenas mensagens de erro ou " +"mais graves para o `stdout`\" e \"enviar apenas mensagens críticas para um " +"endereço de e-mail\". Esse cenário exigiria três manipuladores diferentes, " +"cada um responsável por encaminhar mensagens de uma determinada gravidade " +"para um destino específico." -#: ../../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 manipuladores (veja :ref:`useful-" +"handlers`); os tutoriais usam principalmente :class:`StreamHandler` e :class:" +"`FileHandler` em 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 " "application developers who are using the built-in handler objects (that is, " "not creating custom handlers) are the following configuration methods:" msgstr "" +"Existem pouquíssimos métodos em um manipulador com os quais desenvolvedores " +"de aplicações precisam se preocupar. Para quem está usando manipuladores já " +"inclusos na biblioteca (ou seja, sem criar manipuladores personalizados), os " +"únicos métodos realmente relevantes são os métodos de configuração a seguir:" -#: ../../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. " @@ -811,32 +1123,48 @@ msgid "" "The level set in each handler determines which messages that handler will " "send on." msgstr "" +"O método :meth:`~Handler.setLevel`, assim como acontece nos objetos " +"logger, , define o menor nível de severidade das mensagens que serão " +"encaminhadas para o destino adequado. Mas por que existem dois métodos :meth:" +"`~Handler.setLevel`? Isso acontece porque o nível configurado no logger " +"define quais mensagens ele vai repassar para seus manipuladores. Já o nível " +"configurado em cada manipulador define, entre as mensagens recebidas, quais " +"realmente serão enviadas adiante." -#: ../../howto/logging.rst:533 +#: ../../howto/logging.rst:537 msgid "" ":meth:`~Handler.setFormatter` selects a Formatter object for this handler to " "use." msgstr "" +":meth:`~Handler.setFormatter` define um objeto Formatador para que o " +"manipulador utilize." -#: ../../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 "" +":meth:`~Handler.addFilter` e :meth:`~Handler.removeFilter`, respectivamente, " +"adicionam e removem objetos filtros nos manipuladores." -#: ../../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 " "the interface that all handlers should have and establishes some default " "behavior that child classes can use (or override)." msgstr "" +"O código da aplicação não deve instanciar nem usar diretamente objetos da " +"classe :class:`Handler`. Na verdade, :class:`Handler` é uma classe base que " +"define a interface que todos os manipuladores devem implementar e estabelece " +"um comportamento padrão que pode ser aproveitado (ou sobrescrito) pelas " +"classes filhas." -#: ../../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 " @@ -845,21 +1173,38 @@ msgid "" "takes three optional arguments -- a message format string, a date format " "string and a style indicator." msgstr "" +"Objetos Formatadores definem a ordem, a estrutura e o conteúdo final da " +"mensagem de log. Diferentemente da classe base :class:`logging.Handler`, o " +"código da aplicação pode instanciar classes de formatadores — embora também " +"seja possível criar subclasses, caso sua aplicação precise de um " +"comportamento específico. O construtor aceita três argumentos opcionais: uma " +"string de formato da mensagem, uma string de formatação da data e um " +"indicador de estilo." -#: ../../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 "" +"Se nenhuma string de formato for fornecida na mensagem, o padrão é usar a " +"mensagem bruta. Se nenhuma string de formato de data for definida, o formato " +"de data padrão será:" #: ../../howto/logging.rst:564 +msgid "%Y-%m-%d %H:%M:%S" +msgstr "%Y-%m-%d %H:%M:%S" + +#: ../../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 "" +"com os milissegundos acrescentados ao final. O parâmetro ``style`` pode ser " +"``'%'``, ``'{'`` ou ``'$'``. Se nenhum deles for especificado, o padrão " +"utilizado será ``'%'``." -#: ../../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 :" @@ -868,19 +1213,32 @@ msgid "" "arguments), while if the style is ``'$'`` then the message format string " "should conform to what is expected by :meth:`string.Template.substitute`." msgstr "" +"Se o o parâmetro ``style`` for ``'%'``, a string de formato da mensagem " +"substituirá a string usando o estilo ``%()s``; as " +"chaves possíveis estão documentadas em :ref:`logrecord-attributes`. Se o " +"estilo for ``'{'``, a string de formato é presumida como compatível com :" +"meth:`str.format` (usando argumentos nomeados). Já se o estilo for ``'$'``, " +"a string de formato deverá seguir o que é esperado por :meth:`string." +"Template.substitute`." -#: ../../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 legível 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 "'%(asctime)s - %(levelname)s - %(message)s'" + +#: ../../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 " @@ -890,69 +1248,275 @@ msgid "" "want all logging times to be shown in GMT, set the ``converter`` attribute " "in the Formatter class (to ``time.gmtime`` for GMT display)." msgstr "" +"Formatadores usam uma função configurável pelo usuário para converter o " +"horário de criação de um registro em uma tupla. Por padrão, é utilizada a " +"função :func:`time.localtime`; Se você quiser alterar isso apenas para uma " +"instância específica de formatador, basta definir o atributo ``converter`` " +"dessa instância para uma função com a mesma assinatura de :func:`time." +"localtime` ou :func:`time.gmtime`. Já se a ideia for alterar o comportamento " +"para todos os formatadores (por exemplo, para exibir todos os horários de " +"log em GMT), defina o atributo ``converter`` diretamente na classe " +"Formatadora (usando, por exemplo, ``time.gmtime`` para exibição em GMT)." -#: ../../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 "" +"Criando loggers, manipuladores e formatadores de forma explícita, usando " +"código Python que invoca os métodos de configuração mencionados acima." -#: ../../howto/logging.rst:601 +#: ../../howto/logging.rst:605 msgid "" "Creating a logging config file and reading it using the :func:`fileConfig` " "function." msgstr "" +"Criando um arquivo de configuração de logging e lendo-o usando a função :" +"func:`fileConfig`." -#: ../../howto/logging.rst:603 +#: ../../howto/logging.rst:607 msgid "" "Creating a dictionary of configuration information and passing it to the :" "func:`dictConfig` function." msgstr "" +"Criando um dicionário com as informações de configuração e passando-o para a " +"função :func:`dictConfig`." -#: ../../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 +"Para a documentação de referência sobre as duas últimas opções, consulte :" +"ref:`logging-config-api`. O exemplo a seguir configura um logger bem " +"simples, um manipulador de console e um formatador simples utilizando código " +"Python:" + +#: ../../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 "" +"import logging\n" +"\n" +"# cria o logger\n" +"logger = logging.getLogger('exemplo_simples')\n" +"logger.setLevel(logging.DEBUG)\n" +"\n" +"# cria o manipulador de console e configura o nível para depuração\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.DEBUG)\n" +"\n" +"# cria o formatador\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"\n" +"# adiciona o formatador ao manipulador\n" +"ch.setFormatter(formatter)\n" +"\n" +"# adiciona o manipulador ao logger\n" +"logger.addHandler(ch)\n" +"\n" +"# 'código' da aplicação\n" +"logger.debug('mensagem de depuração')\n" +"logger.info('mensagem informativa')\n" +"logger.warning('mensagem de alerta')\n" +"logger.error('mensagem de erro')\n" +"logger.critical('mensagem crítica')" + +#: ../../howto/logging.rst:640 msgid "" "Running this module from the command line produces the following output:" +msgstr "A execução deste módulo pela linha de comando produz a seguinte saída:" + +#: ../../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 "" +"$ python simple_logging_module.py\n" +"2005-03-19 15:10:26,618 - exemplo_simples - DEBUG - mensagem de depuração\n" +"2005-03-19 15:10:26,620 - exemplo_simples - INFO - mensagem informativa\n" +"2005-03-19 15:10:26,695 - exemplo_simples - WARNING - mensagem de alerta\n" +"2005-03-19 15:10:26,697 - exemplo_simples - ERROR - mensagem de erro\n" +"2005-03-19 15:10:26,773 - exemplo_simples - CRITICAL - mensagem crítica" -#: ../../howto/logging.rst:647 +#: ../../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 +"O módulo Python a seguir cria um logger, um manipulador e um formatador " +"quase idênticos aos do exemplo mostrado acima, sendo a única diferença os " +"nomes dos objetos::" + +#: ../../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 "" +"import logging\n" +"import logging.config\n" +"\n" +"logging.config.fileConfig('logging.conf')\n" +"\n" +"# criação do logger\n" +"logger = logging.getLogger('simpleExample')\n" +"\n" +"# código da 'aplicação'\n" +"logger.debug('mensagem de debug')\n" +"logger.info('mensagem informativa')\n" +"logger.warning('mensagem de cuidado')\n" +"logger.error('mensagem de erro')\n" +"logger.critical('mensagem crítica')" + +#: ../../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 "" +"[loggers]\n" +"keys=root,exemploSimples\n" +"\n" +"[handlers]\n" +"keys=manipuladorConsole\n" +"\n" +"[formatters]\n" +"keys=formatadorSimples\n" +"\n" +"[logger_root]\n" +"level=DEBUG\n" +"handlers=manipuladorConsole\n" +"\n" +"[logger_exemploSimples]\n" +"level=DEBUG\n" +"handlers=manipuladorConsole\n" +"qualname=exemploSimples\n" +"propagate=0\n" +"\n" +"[handler_manipuladorConsole]\n" +"class=StreamHandler\n" +"level=DEBUG\n" +"formatter=formatadorSimples\n" +"args=(sys.stdout,)\n" +"\n" +"[formatter_formatadorSimples]\n" +"format=%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +#: ../../howto/logging.rst:702 msgid "" "The output is nearly identical to that of the non-config-file-based example:" msgstr "" +"A saída é quase idêntica à do exemplo não baseado em arquivo de configuração:" -#: ../../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 "" +"$ python simple_logging_config.py\n" +"2005-03-19 15:38:55,977 - exemploSimples - DEBUG - mensagem de depuração\n" +"2005-03-19 15:38:55,979 - exemploSimples - INFO - mensagem informativa\n" +"2005-03-19 15:38:56,054 - exemploSimples - WARNING - mensagem de alerta\n" +"2005-03-19 15:38:56,055 - exemploSimples - ERROR - mensagem de erro\n" +"2005-03-19 15:38:56,130 - exemploSimples - CRITICAL - mensagem crítica" + +#: ../../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 "" +"A abordagem de usar um arquivo de configuração oferece algumas vantagens em " +"relação ao uso direto de código Python. Ela permite separar a configuração " +"do código, facilitando a manutenção, e também possibilita que pessoas sem " +"conhecimentos de programação modifiquem facilmente as propriedades de " +"logging apenas editando o arquivo de configuração." -#: ../../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 " @@ -962,8 +1526,17 @@ msgid "" "configuration. Please refer to the reference documentation for more " "information, and specify ``False`` for this parameter if you wish." msgstr "" +"A função :func:`fileConfig` possui um parâmetro chamado " +"``disable_existing_loggers``, que por padrão é definido como ``True`` por " +"questões de retrocompatibilidade. No entanto, esse comportamento pode não " +"ser o desejado, pois todos os loggers que não o raiz que já existiam antes " +"da chamada de :func:`fileConfig` serão desativados, a menos que eles (ou " +"algum de seus ancestrais) sejam explicitamente nomeados na configuração. " +"Caso queira manter os loggers preexistentes ativos, basta definir esse " +"parâmetro como ``False``. Para maiores detalhes, consulte a documentação " +"oficial de referência." -#: ../../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 " @@ -971,8 +1544,14 @@ msgid "" "the logger-disabling behaviour described above, which may not be what you " "want - in which case, provide the key explicitly with a value of ``False``." msgstr "" +"O dicionário passado para :func:`dictConfig` também pode especificar um " +"valor booleano com a chave ``disable_existing_loggers``. Se essa chave não " +"for definida explicitamente no dicionário, o valor padrão será interpretado " +"como ``True``. Isso resulta no mesmo comportamento de desativação de loggers " +"descrito anteriormente, o que pode não ser o desejado. Nesse caso, basta " +"informar a chave no dicionário com o valor ``False``." -#: ../../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 " @@ -982,8 +1561,15 @@ msgid "" "module ``mymodule``, where ``mypackage`` is available on the Python import " "path)." msgstr "" +"Observe que os nomes de classe referenciados em arquivos de configuração " +"precisam ser relativos ao módulo logging, ou valores absolutos que possam " +"ser resolvidos pelos mecanismos normais de importação do Python. Por " +"exemplo, você pode usar :class:`~logging.handlers.WatchedFileHandler` " +"(relativo ao módulo logging) ou ``mypackage.mymodule.MyHandler`` (para uma " +"classe definida no pacote ``mypackage`` e no módulo ``mymodule``, desde que " +"``mypackage`` esteja disponível no caminho de importação do Python)." -#: ../../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 " @@ -997,31 +1583,90 @@ msgid "" "can construct the dictionary in Python code, receive it in pickled form over " "a socket, or use whatever approach makes sense for your application." msgstr "" - -#: ../../howto/logging.rst:751 +"A partir do Python 3.2, foi introduzida uma nova forma de configurar o " +"logging, utilizando dicionários para armazenar as informações de " +"configuração. Essa abordagem oferece um conjunto ampliado de funcionalidades " +"em relação ao método baseado em arquivos de configuração mencionado " +"anteriormente, sendo, portanto, a forma recomendada de configuração para " +"novas aplicações e implantações. Como a configuração é mantida em um " +"dicionário Python, há maior flexibilidade sobre as opções de como esse " +"dicionário pode ser construído. É possível, por exemplo, utilizar um arquivo " +"em formato JSON ou YAML, construir o dicionário diretamente em código " +"Python, recebê-lo em forma serializada com pickle por meio de um soquete, ou " +"ainda empregar qualquer outro método que faça sentido para a aplicação em " +"questão." + +#: ../../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 "" +"Aqui está um exemplo da mesma configuração acima, em formato YAML, para a " +"nova abordagem baseada em dicionário:" + +#: ../../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 "" +"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]" -#: ../../howto/logging.rst:775 +#: ../../howto/logging.rst:779 msgid "" "For more information about logging using a dictionary, see :ref:`logging-" "config-api`." msgstr "" +"Para mais informações sobre logging com dicionário, consulte :ref:`logging-" +"config-api`." -#: ../../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 "" +"Se nenhuma configuração de logging for fornecida, pode ocorrer uma situação " +"em que um evento de logging precise ser registrado, mas nenhum manipulador " +"esteja disponível para processar e exibir esse evento." -#: ../../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 " @@ -1032,33 +1677,49 @@ msgid "" "handler's level is set to ``WARNING``, so all events at this and greater " "severities will be output." msgstr "" - -#: ../../howto/logging.rst:796 +"O evento é exibido utilizando um “manipulador de último recurso”, armazenado " +"em :data:`lastResort`. Esse manipulador interno não está associado a nenhum " +"logger e funciona como um :class:`~logging.StreamHandler`, enviando a " +"mensagem de descrição do evento para o valor atual de ``sys.stderr`` " +"(espeitando, portanto, quaisquer redirecionamentos que estejam em vigor). " +"Nenhuma formatação é aplicada à mensagem — apenas a descrição bruta do " +"evento é impressa. O nível desse manipulador é definido como ``WARNING``, de " +"forma que todos os eventos nesse nível ou em níveis mais severos serão " +"exibidos." + +#: ../../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 "" +"Se :data:`raiseExceptions` for ``False`` (modo em produção), o evento será " +"silenciosamente descartado." -#: ../../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 "" +"Se :data:`raiseExceptions` for definido como ``True`` (modo de " +"desenvolvimento), a mensagem 'No handlers could be found for logger X.Y.Z' " +"será exibida uma vez." -#: ../../howto/logging.rst:804 +#: ../../howto/logging.rst:808 msgid "" "To obtain the pre-3.2 behaviour, :data:`lastResort` can be set to ``None``." msgstr "" +"Para obter o comportamento pré-versão-3.2, :data:`lastResort` pode ser " +"definido como ``None``." -#: ../../howto/logging.rst:810 +#: ../../howto/logging.rst:814 msgid "Configuring Logging for a Library" -msgstr "" +msgstr "Configurando logging para uma biblioteca" -#: ../../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 " @@ -1068,8 +1729,17 @@ msgid "" "of severity ``WARNING`` and greater will be printed to ``sys.stderr``. This " "is regarded as the best default behaviour." msgstr "" +"Ao desenvolver um biblioteca que usa logging, é importante documentar como a " +"biblioteca usa o recurso - por exemplo, os nomes dos loggers usados. Também " +"é necessário levar em consideração a configuração de logging. Caso a " +"aplicação que utiliza a biblioteca não faça uso de logging e o código da " +"biblioteca execute chamadas de logging, então os eventos de severidade " +"``WARNING`` e níveis mais severos serão impressos em ``sys.stderr`` ." +"(conforme descrito na seção anterior). Isso garante que mensagens " +"importantes não sejam perdidas, como comportamento padrão, mesmo que a " +"aplicação principal não configure explicitamente o sistema de logging." -#: ../../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-" @@ -1080,8 +1750,18 @@ msgid "" "suitably configured then logging calls made in library code will send output " "to those handlers, as normal." msgstr "" +"Se, por algum motivo, você *não* quiser que essas mensagens sejam exibidas " +"na ausência de qualquer configuração de logging, pode anexar um manipulador " +"que não faz nada ao logger de nível superior da sua biblioteca. Dessa forma, " +"evita-se que a mensagem seja impressa, já que sempre haverá um manipulador " +"associado aos eventos da biblioteca — apenas não produzirá saída. Caso o " +"usuário da biblioteca configure o logging para uso na aplicação, essa " +"configuração provavelmente incluirá alguns manipuladores adicionais e, se os " +"níveis forem configurados adequadamente, as chamadas de logging feitas no " +"código da biblioteca enviarão a saída para esses manipuladores, funcionando " +"normalmente." -#: ../../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 " @@ -1091,15 +1771,34 @@ msgid "" "library *foo* is done using loggers with names matching 'foo.x', 'foo.x.y', " "etc. then the code::" msgstr "" +"Um manipulador-que-não-faz-nada já está incluso no pacote :class:`~logging." +"NullHandler` (desde Python 3.1). Uma instância desse manipulador poderia ser " +"adicionado ao logger de nível superior do espaço de nomes de logging usado " +"pelo biblioteca (*se* você quiser evitar que os eventos registrados do " +"biblioteca sejam enviados para ``sys.stderr``, na ausência de configuração " +"de logging). Se todo registro em log de uma biblioteca *foo* for feito " +"usando loggers com nomes correspondente 'foo.x', 'foo.x.y' etc., então o " +"código::" -#: ../../howto/logging.rst:840 +#: ../../howto/logging.rst:841 +msgid "" +"import logging\n" +"logging.getLogger('foo').addHandler(logging.NullHandler())" +msgstr "" +"import logging\n" +"logging.getLogger('foo').addHandler(logging.NullHandler())" + +#: ../../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 "" +"deve resultar no efeito desejado. Se uma organização produzir vários " +"bibliotecas, o nome do logger especificado poderá ser 'orgname.foo' em vez " +"de apenas 'foo'." -#: ../../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, " @@ -1108,8 +1807,14 @@ msgid "" "application developer to configure the logging verbosity or handlers of your " "library as they wish." msgstr "" +"É altamente recomendável que você *não registre logs no logger raiz* do seu " +"biblioteca. Em vez disso, use um logger com um nome exclusivo e facilmente " +"identificável, como o ``__name__`` do nível superior do seu pacote/módulo da " +"biblioteca. O registro em log no logger raiz dificultará, ou mesmo tornará " +"impossível que o desenvolvedor da aplicação personalize o manipulador e a " +"verbosidade de logging." -#: ../../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 " @@ -1119,12 +1824,19 @@ msgid "" "handlers 'under the hood', you might well interfere with their ability to " "carry out unit tests and deliver logs which suit their requirements." msgstr "" +"É altamente recomendável que você *não adicione outros manipuladores além " +"de* :class:`~logging.NullHandler` *nos loggers da sua biblioteca*. Isso " +"porque a configuração de manipuladores é responsabilidade do desenvolvedor " +"da aplicação que utilizará ela. O desenvolvedor sabe o público-alvo da " +"aplicação final, e, portanto, sabe também quais são os manipuladores mais " +"adequados para o caso. Se você adicionar manipuladores 'ocultos', poderá " +"interferir na criação de testes unitários e na entrega de logs úteis." -#: ../../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 +1844,45 @@ msgid "" "define a level with the same numeric value, it overwrites the predefined " "value; the predefined name is lost." msgstr "" +"Os valores numéricos 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 numérico, ele " +"sobrescreve 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 " @@ -1174,15 +1891,26 @@ msgid "" "the method call's, no logging message is actually generated. This is the " "basic mechanism controlling the verbosity of logging output." msgstr "" +"Os níveis também podem ser associados aos registradores, sendo definidos " +"pelo desenvolvedor ou por meio do carregamento de uma configuração salva. " +"Quando um método de logging é invocado em um logger, o logger compara o seu " +"próprio nível com o nível associado à chamada do método. Se o nível do " +"logger for maior do que o da chamada do método, nenhuma mensagem será " +"gerada. Esse é o mecanismo básico que controla a verbosidade da saída de " +"logging." -#: ../../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 "" +"As mensagens de logging são representadas como instâncias da classe :class:" +"`~logging.LogRecord`. Quando um logger decide registrar um evento, uma " +"instância de :class:`~logging.LogRecord` é criada a partir da mensagem de " +"logging." -#: ../../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` " @@ -1198,8 +1926,22 @@ msgid "" "message (unless the *propagate* flag for a logger is set to a false value, " "at which point the passing to ancestor handlers stops)." msgstr "" - -#: ../../howto/logging.rst:911 +"As mensagens de logging passam por um mecanismo de despacho que utiliza :dfn:" +"`manipuladores`, que são instâncias de subclasses da classe :class:" +"`Handler`. Manipuladores são responsáveis por assegurar que uma mensagem " +"registrada em log (na forma de :class:`LogRecord`) seja encaminhada para um " +"determinado destino (ou conjunto de destinos) que serão úteis para o público-" +"alvo daquela mensagem (como usuários finais, equipe de suporte, " +"administradores do sistema e desenvolvedores). Manipuladores transmitem :" +"class:`LogRecord` para destinos específicos. Cada logger pode ter zero, um " +"ou mais manipuladores associados à ele (através do método :meth:`~Logger." +"addHandler` de :class:`Logger`). Além disso, não são apenas os manipuladores " +"diretamente associados a um logger que processam a mensagem. Por padrão, os " +"manipuladores de todos os loggers ancestrais também participam do despacho. " +"Essa propagação só é interrompida se o atributo *propagate* do logger " +"estiver definido como ``False``." + +#: ../../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. " @@ -1208,12 +1950,18 @@ msgid "" "defined subclasses of :class:`Handler` will need to override this :meth:" "`~Handler.emit`." msgstr "" +"Assim como os loggers, os manipuladores também podem ter níveis associados. " +"O nível de um manipulador funciona como um filtro, do mesmo modo que o nível " +"de um logger. Quando um manipulador decide processar um evento, ele utiliza " +"o método :meth:`~Handler.emit` para enviar a mensagem ao seu destino. Na " +"maioria dos casos, subclasses personalizadas de :class:`Handler` precisarão " +"substituir esse método :meth:`~Handler.emit`." -#: ../../howto/logging.rst:920 +#: ../../howto/logging.rst:924 msgid "Custom Levels" -msgstr "" +msgstr "Níveis personalizados" -#: ../../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. " @@ -1225,12 +1973,21 @@ msgid "" "difficult for the using developer to control and/or interpret, because a " "given numeric value might mean different things for different libraries." msgstr "" - -#: ../../howto/logging.rst:935 +"Criar seus próprios níveis é possível, mas não deve ser necessário, pois os " +"níveis existentes foram escolhidos com base na experiência prática. No " +"entanto, se for estritamente necessário, tome cuidado para fazer. E se você " +"está *desenvolvendo uma biblioteca, não é recomendado que defina níveis " +"personalizados*. Isso porque, se vários autores de biblioteca definirem seus " +"próprios níveis personalizados, as saídas de logging das bibliotecas em " +"conjunto serão orquestradas com maior dificuldade pelo desenvolvedor, pois " +"um determinado valor numérico poderá significar coisas diferentes para " +"diferentes bibliotecas." + +#: ../../howto/logging.rst:939 msgid "Useful Handlers" -msgstr "" +msgstr "Handlers úteis" -#: ../../howto/logging.rst:937 +#: ../../howto/logging.rst:941 msgid "" "In addition to the base :class:`Handler` class, many useful subclasses are " "provided:" @@ -1238,93 +1995,132 @@ 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 "" +":class:`StreamHandler`, quando instanciadas, enviam mensagens para streams " +"(objeto arquivo ou similar)." -#: ../../howto/logging.rst:943 +#: ../../howto/logging.rst:947 msgid ":class:`FileHandler` instances send messages to disk files." msgstr "" +":class:`FileHandler`, quando instanciadas, enviam mensagens para arquivos " +"locais de disco." -#: ../../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 " "directly. Instead, use :class:`~handlers.RotatingFileHandler` or :class:" "`~handlers.TimedRotatingFileHandler`." msgstr "" +":class:`~handlers.BaseRotatingHandler` é a classe base para objetos handler " +"que rotacionam os arquivos de logging em um determinado ponto. Não é feita " +"para ser instanciada diretamente. Em vez disso, use :class:`~handlers." +"RotatingFileHandler` ou :class:`~handlers.TimedRotatingFileHandler`." -#: ../../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 "" +":class:`~handlers.RotatingFileHandler`, quando instanciadas, enviam " +"mensagens para arquivos locais de disco. Permite definir o tamanho máximo do " +"arquivo de log e configurar rotação." -#: ../../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 "" +":class:`~handlers.TimedRotatingFileHandler`, quando instanciadas, enviam " +"mensagens para arquivos locais de disco, rotacionando o arquivo de log em " +"certos intervalos de tempo." -#: ../../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 "" +":class:`~handlers.SocketHandler`, quando instanciadas, enviam mensagens para " +"soquetes TCP/IP. Desde a versão 3.4, os soquetes de domínio Unix também são " +"suportados." -#: ../../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 "" +":class:`~handlers.DatagramHandler`, quando instanciadas, enviam mensagens " +"para soquetes UDP. Desde a versão 3.4, os soquetes de domínio Unix também " +"são suportados." -#: ../../howto/logging.rst:962 +#: ../../howto/logging.rst:966 msgid "" ":class:`~handlers.SMTPHandler` instances send messages to a designated email " "address." msgstr "" +":class:`~handlers.SMTPHandler`, quando instanciadas, enviam mensagens para " +"endereços de e-mail pré-definidos." -#: ../../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 "" +":class:`~handlers.SysLogHandler`, quando instanciadas, enviam mensagens para " +"um daemon syslog Unix, normalmente em um computador remoto." -#: ../../howto/logging.rst:968 +#: ../../howto/logging.rst:972 msgid "" ":class:`~handlers.NTEventLogHandler` instances send messages to a Windows " "NT/2000/XP event log." msgstr "" +":class:`~handlers.NTEventLogHandler`, quando instanciadas, enviam mensagens " +"para um registro de log do Windows NT/2000/XP." -#: ../../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 "" +":class:`~handlers.MemoryHandler`, quando instanciadas, enviam mensagens para " +"um buffer na memória, que é liberado sempre que alguns critérios específicos " +"são atendidos." -#: ../../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 "" +":class:`~handlers.HTTPHandler`, quando instanciadas, enviam mensagens para " +"um servidor HTTP, utilizando os métodos ``GET`` ou ``POST``." -#: ../../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 " "name. This handler is only useful on Unix-like systems; Windows does not " "support the underlying mechanism used." msgstr "" +":class:`~handlers.WatchedFileHandler`, quando instanciadas, observam o " +"arquivo que estão fazendo logging. Se o arquivo for alterado, ele será " +"fechado e reaberto com o mesmo nome. Este manipulador só é funcional em " +"sistemas Unix ou similares; o Windows não oferece suporte ao mecanismo " +"subjacente utilizado." -#: ../../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 "" +":class:`~handlers.QueueHandler`, quando instanciadas, enviam mensagem para " +"uma fila, que pode ser implementada com o módulo :mod:`queue` ou com o " +"módulo :mod:`multiprocessing`." -#: ../../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 " @@ -1332,39 +2128,57 @@ msgid "" "the library user has not configured logging. See :ref:`library-config` for " "more information." msgstr "" +":class:`NullHandler`, quando instanciadas, não fazem nada com as mensagens " +"de erro. Elas são usadas por desenvolvedores da biblioteca que precisam usar " +"o logging, mas querem evitar o aviso 'No handlers could be found for logger " +"*XXX*', que pode ser exibido quando o logging não é configurado. Veja :ref:" +"`library-config` para mais informações." -#: ../../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 " "defined in a sub-module, :mod:`logging.handlers`. (There is also another sub-" "module, :mod:`logging.config`, for configuration functionality.)" msgstr "" +"As subclasses :class:`NullHandler`, :class:`StreamHandler` e :class:" +"`FileHandler` são definidas no pacote base de logging. Os outros " +"manipuladores são definidos no submódulo :mod:`logging.handlers`. (Existe " +"também outro submódulo, :mod:`logging.config`, para configurar as " +"funcionalidades)." -#: ../../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 "" +"As mensagens de log são formatadas por meio de instâncias da classe :class:" +"`Formatter`. Elas são inicializadas com uma string de formato, que pode ser " +"usada junto com o operador % e um dicionário para substituir os valores na " +"mensagem." -#: ../../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 " "applied to each message in the batch), there is provision for header and " "trailer format strings." msgstr "" +"Para formatar várias mensagens em um lote, podem ser usadas instâncias de :" +"class:`BufferingFormatter`. Além de aplicar string de formato em cada " +"mensagem do lote, é possível definir strings de formato para o cabeçalho e o " +"rodapé do lote." -#: ../../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:" @@ -1373,55 +2187,83 @@ msgid "" "consult all their filters for permission. If any filter returns a false " "value, the message is not processed further." msgstr "" +"Quando não for suficiente fazer a filtragem baseada no nível do logger e/ou " +"no nível de manipulador, instâncias de :class:`Filter` poderão ser " +"adicionadas às instâncias de :class:`Logger` e :class:`Handler` (por meio do " +"método :meth:`~Handler.addFilter`). Antes de processar uma mensagem, os " +"loggers e manipuladores consultam todos os seus filtros para obter " +"permissão. Se algum filtro retornar um valor falso, a mensagem não é " +"processada." -#: ../../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 "" +"A funcionalidade básica do :class:`Filter` permite a filtragem por um nome " +"específico de logger. Se este recurso for usado, as mensagens enviadas para " +"o logger com esse nome, ou seus descendentes, serão permitidas pelo filtro. " +"E todas as outras são descartadas." -#: ../../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 " "logging events - such as logging misconfiguration, network or other similar " "errors - do not cause the application using logging to terminate prematurely." msgstr "" +"O pacote de logging foi projetado para inibir exceções que possam ocorrer " +"quando os registros forem feitos em produção. Desta forma, a aplicação que " +"está utilizando logging não encerrará abruptamente caso hajam erros nos " +"eventos de logging - devido a problemas como má configuração, rede ou " +"outros." -#: ../../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` " "method of a :class:`Handler` subclass are passed to its :meth:`~Handler." "handleError` method." msgstr "" +"As exceções :class:`SystemExit` e :class:`KeyboardInterrupt` nunca são " +"inibidas. Outras exceções que possam ocorrem durante o método :meth:" +"`~Handler.emit` de uma subclasse de :class:`Handler` são passadas para seus " +"respectivos métodos :meth:`~Handler.handleError`." -#: ../../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`, " "is set. If set, a traceback is printed to :data:`sys.stderr`. If not set, " "the exception is swallowed." msgstr "" +"A implementação padrão de :meth:`~Handler.handleError` em :class:`Handler` " +"verifica se uma variável de módulo, :data:`raiseExceptions`, está definida. " +"Caso esteja, um traceback (situação da pilha de execução) é exibido em :data:" +"`sys.stderr`. Se não, a exceção é inibida." -#: ../../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 " "occur. It's advised that you set :data:`raiseExceptions` to ``False`` for " "production usage." msgstr "" +"O valor padrão de :data:`raiseExceptions` é ``verdadeiro``. Isso ocorre " +"porque, durante o desenvolvimento, você normalmente desejará ser notificado " +"sobre qualquer exceção que ocorra. É recomendável que você defina :data:" +"`raiseExceptions` como ``falso`` para usos em produção." -#: ../../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 " @@ -1432,12 +2274,20 @@ msgid "" "`~handlers.SocketHandler` emits an event by pickling it and sending it over " "the wire." msgstr "" +"Nas seções e exemplos anteriores, todas as mensagens criadas ao realizar o " +"logging de um evento foram instanciadas como string. No entanto, essa não é " +"a única possibilidade. Você pode passar um objeto arbitrário como mensagem, " +"e seu método :meth:`~object.__str__` será chamado quando o sistema de " +"logging precisar convertê-lo em uma string. Inclusive, é possível evitar " +"totalmente o uso de uma representação em string - por exemplo, a classe :" +"class:`~handlers.SocketHandler` emite a mensagem enviando pela rede sua " +"respectiva serialização com pickle." -#: ../../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 " @@ -1447,14 +2297,33 @@ msgid "" "event would be created by the Logger for that level of call. You can write " "code like this::" msgstr "" +"A formatação dos argumentos das mensagem é adiada até o quanto for possível. " +"No entanto, o processamento dos argumentos para o método de logging pode ser " +"custoso, e talvez você queira evitar fazê-lo, se o logging for descartar o " +"evento. Para decidir o que fazer, você pode chamar o método :meth:`~Logger." +"isEnabledFor`, que recebe um nível como argumento e retorna verdadeiro " +"apenas se o evento tiver sido criado pelo logger para esse nível em " +"específico. Desta forma, você pode escrever algo como:" #: ../../howto/logging.rst:1081 msgid "" +"if logger.isEnabledFor(logging.DEBUG):\n" +" logger.debug('Message with %s, %s', expensive_func1(),\n" +" expensive_func2())" +msgstr "" +"if logger.isEnabledFor(logging.DEBUG):\n" +" logger.debug('Mensagem com %s, %s', func_custosa1(),\n" +" func_custosa2())" + +#: ../../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 "" +"desta forma, se o limite do logger for definido acima de ``DEBUG``, as " +"chamadas para ``func_custosa1`` e ``func_custosa2`` nunca serão feitas." -#: ../../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 " @@ -1465,103 +2334,126 @@ msgid "" "need to be recomputed when the logging configuration changes dynamically " "while the application is running (which is not all that common)." msgstr "" +"Em alguns casos, o próprio :meth:`~Logger.isEnabledFor` pode ser mais " +"custoso do que você gostaria (por exemplo, para loggers profundamente " +"aninhados, em que um nível explícito só é definido no logger mais alto da " +"hierarquia). Nesses casos (ou se você quiser evitar chamar um método em um " +"laço), é possível cachear o resultado de uma chamada para :meth:`~Logger." +"isEnabledFor` em uma variável local ou instância, e usá-lo em vez de chamar " +"o método todas as vezes. Este valor armazenado só precisaria ser recalculado " +"se a configuração do logger fosse alterada dinamicamente, com a aplicação em " +"execução (o que não é comum)." -#: ../../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. " "Here's a list of things you can do to avoid processing during logging which " "you don't need:" msgstr "" +"Existem outras otimizações que podem ser feitas para aplicação específicas " +"que precisam de um controle mais preciso sobre quais informações de logging " +"são registradas. Abaixo encontra-se uma lista de coisas que você pode fazer " +"para evitar o processamento desnecessário para loggings que serão " +"descartados:" -#: ../../howto/logging.rst:1099 +#: ../../howto/logging.rst:1103 msgid "What you don't want to collect" -msgstr "O que você não quer coletar" +msgstr "O que você não quer registrar" -#: ../../howto/logging.rst:1099 +#: ../../howto/logging.rst:1103 msgid "How to avoid collecting it" -msgstr "" +msgstr "Como evitar o registro" -#: ../../howto/logging.rst:1101 +#: ../../howto/logging.rst:1105 msgid "Information about where calls were made from." -msgstr "" +msgstr "Informações sobre o ponto em que as chamadas foram feitas." -#: ../../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 "" +"Defina ``logging._srcfile`` como ``None``. Isso evita chamar :func:`sys." +"_getframe`, o que pode acelerar seu código em ambientes como o PyPy (que não " +"consegue acelerar códigos que usam :func:`sys._getframe`)." -#: ../../howto/logging.rst:1107 +#: ../../howto/logging.rst:1111 msgid "Threading information." -msgstr "" +msgstr "Informações sobre threading." -#: ../../howto/logging.rst:1107 +#: ../../howto/logging.rst:1111 msgid "Set ``logging.logThreads`` to ``False``." -msgstr "" +msgstr "Defina ``logging.logThreads`` como ``False``." -#: ../../howto/logging.rst:1109 +#: ../../howto/logging.rst:1113 msgid "Current process ID (:func:`os.getpid`)" -msgstr "" +msgstr "ID do processo atual (:func:`os.getpid`)" -#: ../../howto/logging.rst:1109 +#: ../../howto/logging.rst:1113 msgid "Set ``logging.logProcesses`` to ``False``." -msgstr "" +msgstr "Defina ``logging.logProcesses`` como ``False``." -#: ../../howto/logging.rst:1111 +#: ../../howto/logging.rst:1115 msgid "" "Current process name when using ``multiprocessing`` to manage multiple " "processes." msgstr "" +"Nome do processo atual, ao utilizar o módulo ``multiprocessing`` para " +"gerenciar múltiplos processamentos." -#: ../../howto/logging.rst:1111 +#: ../../howto/logging.rst:1115 msgid "Set ``logging.logMultiprocessing`` to ``False``." -msgstr "" +msgstr "Defina ``logging.logMultiprocessing`` como ``False``." -#: ../../howto/logging.rst:1114 +#: ../../howto/logging.rst:1118 msgid "Current :class:`asyncio.Task` name when using ``asyncio``." msgstr "" +"Nome da tarefa :class:`asyncio.Task` atual, ao utilizar o módulo ``asyncio``." -#: ../../howto/logging.rst:1114 +#: ../../howto/logging.rst:1118 msgid "Set ``logging.logAsyncioTasks`` to ``False``." -msgstr "" +msgstr "Defina ``logging.logAsyncioTasks`` como ``False``." -#: ../../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 "" +"Observe também que o módulo base de logging inclui apenas o manipulador " +"básico. Se você não importar :mod:`logging.handlers` e :mod:`logging." +"config`, eles não ocuparão nenhum espaço da memória." -#: ../../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..571a0f745 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..39bafff9d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..dabf7878e 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0907534ea 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,17 +884,17 @@ 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." #: ../../howto/regex.rst:363 ../../howto/regex.rst:417 -#: ../../howto/regex.rst:1065 +#: ../../howto/regex.rst:1069 msgid "Method/Attribute" msgstr "Método/Atributo" #: ../../howto/regex.rst:363 ../../howto/regex.rst:417 -#: ../../howto/regex.rst:1065 +#: ../../howto/regex.rst:1069 msgid "Purpose" msgstr "Propósito" @@ -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 "" @@ -1828,20 +2407,24 @@ msgstr "" "tentativas incorretas:" #: ../../howto/regex.rst:1016 +msgid "``.*[.][^b].*$``" +msgstr "``.*[.][^b].*$``" + +#: ../../howto/regex.rst:1018 msgid "" -"``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by " -"requiring that the first character of the extension is not a ``b``. This is " -"wrong, because the pattern also doesn't match ``foo.bar``." +"The first attempt above tries to exclude ``bat`` by 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 " +"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 +#: ../../howto/regex.rst:1022 msgid "``.*[.]([^b]..|.[^a].|..[^t])$``" msgstr "``.*[.]([^b]..|.[^a].|..[^t])$``" -#: ../../howto/regex.rst:1022 +#: ../../howto/regex.rst:1024 msgid "" "The expression gets messier when you try to patch up the first solution by " "requiring one of the following cases to match: the first character of the " @@ -1859,11 +2442,11 @@ msgstr "" "uma extensão de duas letras, tal como ``sendmail.cf``. Nós iremos complicar " "o padrão novamente em um esforço para corrigi-lo." -#: ../../howto/regex.rst:1030 +#: ../../howto/regex.rst:1032 msgid "``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``" msgstr "``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``" -#: ../../howto/regex.rst:1032 +#: ../../howto/regex.rst:1034 msgid "" "In the third attempt, the second and third letters are all made optional in " "order to allow matching extensions shorter than three characters, such as " @@ -1873,56 +2456,59 @@ msgstr "" "opcionais, a fim de permitir correspondência com as extensões mais curtas do " "que três caracteres, tais como ``sendmail.cf``." -#: ../../howto/regex.rst:1036 +#: ../../howto/regex.rst:1038 msgid "" "The pattern's getting really complicated now, which makes it hard to read " "and understand. Worse, if the problem changes and you want to exclude both " "``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 +#: ../../howto/regex.rst:1043 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 +#: ../../howto/regex.rst:1045 +msgid "``.*[.](?!bat$)[^.]*$``" +msgstr "``.*[.](?!bat$)[^.]*$``" + +#: ../../howto/regex.rst:1047 msgid "" -"``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression " -"``bat`` doesn't match at this point, try the rest of the pattern; if " -"``bat$`` does match, the whole pattern will fail. The trailing ``$`` is " -"required to ensure that something like ``sample.batch``, where the extension " -"only starts with ``bat``, will be allowed. The ``[^.]*`` makes sure that " -"the pattern works when there are multiple dots in the filename." +"The negative lookahead means: if the expression ``bat`` doesn't match at " +"this point, try the rest of the pattern; if ``bat$`` does match, the whole " +"pattern will fail. The trailing ``$`` is required to ensure that something " +"like ``sample.batch``, where the extension 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." +"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 +#: ../../howto/regex.rst:1054 msgid "" "Excluding another filename extension is now easy; simply add it as an " "alternative inside the assertion. The following pattern excludes filenames " "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 +#: ../../howto/regex.rst:1058 msgid "``.*[.](?!bat$|exe$)[^.]*$``" msgstr "``.*[.](?!bat$|exe$)[^.]*$``" -#: ../../howto/regex.rst:1058 +#: ../../howto/regex.rst:1062 msgid "Modifying Strings" -msgstr "Modificando Strings" +msgstr "Modificando strings" -#: ../../howto/regex.rst:1060 +#: ../../howto/regex.rst:1064 msgid "" "Up to this point, we've simply performed searches against a static string. " "Regular expressions are also commonly used to modify strings in various " @@ -1932,21 +2518,21 @@ msgstr "" "estática. As expressões regulares também são comumente usadas para modificar " "strings através de várias maneiras, usando os seguintes métodos padrão:" -#: ../../howto/regex.rst:1067 +#: ../../howto/regex.rst:1071 msgid "``split()``" msgstr "``split()``" -#: ../../howto/regex.rst:1067 +#: ../../howto/regex.rst:1071 msgid "Split the string into a list, splitting it wherever the RE matches" msgstr "" "Divide a string em uma lista, dividindo-a onde quer que haja correspondência " "com a RE" -#: ../../howto/regex.rst:1070 +#: ../../howto/regex.rst:1074 msgid "``sub()``" msgstr "``sub()``" -#: ../../howto/regex.rst:1070 +#: ../../howto/regex.rst:1074 msgid "" "Find all substrings where the RE matches, and replace them with a different " "string" @@ -1954,21 +2540,23 @@ msgstr "" "Encontra todas as substrings que correspondem com a RE e faz a substituição " "por uma string diferente" -#: ../../howto/regex.rst:1073 +#: ../../howto/regex.rst:1077 msgid "``subn()``" msgstr "``subn()``" -#: ../../howto/regex.rst:1073 +#: ../../howto/regex.rst:1077 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 +#: ../../howto/regex.rst:1084 msgid "Splitting Strings" -msgstr "Dividindo as Strings" +msgstr "Dividindo as strings" -#: ../../howto/regex.rst:1082 +#: ../../howto/regex.rst:1086 msgid "" "The :meth:`~re.Pattern.split` method of a pattern splits a string apart " "wherever the RE matches, returning a list of the pieces. It's similar to " @@ -1977,20 +2565,27 @@ 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 que pode usar para fazer a " +"divisão; :meth:`!split` só implementa a divisão por 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 +#: ../../howto/regex.rst:1097 msgid "" "Split *string* by the matches of the regular expression. If capturing " "parentheses are used in the RE, then their contents will also be returned as " "part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* " "splits are performed." msgstr "" -"Divide a string usando a correspondência com uma expressão regular. Se os " +"Divide *string* usando a correspondência com uma expressão regular. Se os " "parênteses de captura forem utilizados na RE, então seu conteúdo também será " -"retornado como parte da lista resultante. Se maxsplit é diferente de zero, " -"um número de divisões ``maxsplit`` será executado." +"retornado como parte da lista resultante. Se *maxsplit* é diferente de zero, " +"serão feitas no máximo *maxplit* divisões." -#: ../../howto/regex.rst:1098 +#: ../../howto/regex.rst:1102 msgid "" "You can limit the number of splits made, by passing a value for *maxsplit*. " "When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the " @@ -1999,85 +2594,179 @@ msgid "" "characters. ::" msgstr "" "Você pode limitar o número de divisões feitas, passando um valor para " -"maxsplit. Quando ``maxsplit`` é diferente de zero, um determinado número de " -"divisões ``maxsplit`` será executado, e o restante da string é retornado " -"como o elemento final da lista. No exemplo a seguir, o delimitador é " -"qualquer sequência de caracteres não alfanuméricos. ::" +"*maxsplit*. Quando *maxsplit* é diferente de zero, serão feita no máximo " +"``maxsplit`` divisões, e o restante da string é retornado como o elemento " +"final da lista. No exemplo a seguir, o delimitador é qualquer sequência de " +"caracteres não alfanuméricos. ::" -#: ../../howto/regex.rst:1110 +#: ../../howto/regex.rst:1108 +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 "" +">>> 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().']" + +#: ../../howto/regex.rst:1114 msgid "" "Sometimes you're not only interested in what the text between delimiters is, " "but also need to know what the delimiter was. If capturing parentheses are " "used in the RE, then their values are also returned as part of the list. " "Compare the following calls::" msgstr "" -"Às vezes, você não está apenas interessado no que o texto que está entre " -"delimitadores contém, mas também precisa saber qual o delimitador foi usado. " -"Se os parênteses de captura são utilizados na RE, então os respectivos " -"valores são também retornados como parte da lista. Compare as seguintes " -"chamadas::" +"Às vezes, você não está interessado apenas no texto que está entre os " +"delimitadores, mas também precisa saber qual o delimitador foi usado. Se os " +"parênteses de captura são utilizados na RE, então os respectivos valores são " +"também retornados como parte da lista. Compare as seguintes chamadas::" -#: ../../howto/regex.rst:1122 +#: ../../howto/regex.rst:1119 +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 "" +">>> 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', '.', '']" + +#: ../../howto/regex.rst:1126 msgid "" "The module-level function :func:`re.split` adds the RE to be used as the " "first argument, but is otherwise the same. ::" 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. ::" +"como o primeiro argumento, mas, fora isso, é a mesma. ::" + +#: ../../howto/regex.rst:1129 +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 "" +">>> 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.']" -#: ../../howto/regex.rst:1134 +#: ../../howto/regex.rst:1138 msgid "Search and Replace" msgstr "Busca e Substituição" -#: ../../howto/regex.rst:1136 +#: ../../howto/regex.rst:1140 msgid "" "Another common task is to find all the matches for a pattern, and replace " "them with a different string. The :meth:`~re.Pattern.sub` method takes a " "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 +#: ../../howto/regex.rst:1147 msgid "" "Returns the string obtained by replacing the leftmost non-overlapping " "occurrences of the RE in *string* by the replacement *replacement*. If the " "pattern isn't found, *string* is returned unchanged." msgstr "" "Retorna a string obtida substituindo as ocorrências mais à esquerda não " -"sobrepostas da RE em ``string`` pela substituição ``replacement``. Se o " -"padrão não for encontrado, a ``string`` é retornada inalterada." +"sobrepostas da RE em ``string`` pelo valor de substituição ``replacement``. " +"Se o padrão não for encontrado, a ``string`` é retornada inalterada." -#: ../../howto/regex.rst:1147 +#: ../../howto/regex.rst:1151 msgid "" "The optional argument *count* is the maximum number of pattern occurrences " "to be replaced; *count* must be a non-negative integer. The default value " "of 0 means to replace all occurrences." msgstr "" -"O argumento opcional ``count`` é o número máximo de ocorrências do padrão a " -"ser substituído; ``count`` deve ser um número inteiro não negativo. O valor " -"padrão ``0`` significa para substituir todas as ocorrências." +"O argumento opcional *count* é o número máximo de ocorrências do padrão a " +"ser substituído; *count* deve ser um número inteiro não negativo. O valor " +"padrão 0 significa substituir todas as ocorrências." -#: ../../howto/regex.rst:1151 +#: ../../howto/regex.rst:1155 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:1160 +#: ../../howto/regex.rst:1158 +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 "" +">>> 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'" + +#: ../../howto/regex.rst:1164 msgid "" "The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-" "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: uma string com novo valor e o número de " +"substituições que foram realizadas:" -#: ../../howto/regex.rst:1169 +#: ../../howto/regex.rst:1167 +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 "" +">>> 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)" + +#: ../../howto/regex.rst:1173 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:1176 msgid "" +">>> p = re.compile('x*')\n" +">>> p.sub('-', 'abxd')\n" +"'-a-b--d-'" +msgstr "" +">>> p = re.compile('x*')\n" +">>> p.sub('-', 'abxd')\n" +"'-a-b--d-'" + +#: ../../howto/regex.rst:1180 +msgid "" "If *replacement* is a string, any backslash escapes in it are processed. " "That is, ``\\n`` is converted to a single newline character, ``\\r`` is " "converted to a carriage return, and so forth. Unknown escapes such as " @@ -2086,17 +2775,34 @@ msgid "" "incorporate portions of the original text in the resulting replacement " "string." msgstr "" +"Se o valor de 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, 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 +#: ../../howto/regex.rst:1187 msgid "" "This example matches the word ``section`` followed by a string enclosed in " "``{``, ``}``, and changes ``section`` to ``subsection``::" msgstr "" "Este exemplo corresponde com a palavra ``section``, seguida por uma string " -"colocada entre ``{, }`` e altera ``section`` para ``subsection``::" +"colocada entre ``{``, ``}``, e altera ``section`` para ``subsection``::" #: ../../howto/regex.rst:1190 msgid "" +">>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First} section{second}')\n" +"'subsection{First} subsection{second}'" +msgstr "" +">>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First} section{second}')\n" +"'subsection{First} subsection{second}'" + +#: ../../howto/regex.rst:1194 +msgid "" "There's also a syntax for referring to named groups as defined by the ``(?" "P...)`` syntax. ``\\g`` will use the substring matched by the " "group named ``name``, and ``\\g`` uses the corresponding group " @@ -2109,14 +2815,32 @@ msgstr "" "Há também uma sintaxe para se referir a grupos nomeados como definido pela " "sintaxe ``(?P...)``. ``\\g`` usará a substring correspondida " "pelo grupo com nome ``name`` e ``\\g`` utiliza o número do grupo " -"correspondente. ``.\\g<2>`` é, portanto, equivalente a ``\\2``, mas não é " -"ambígua em uma string de substituição (replacement), tal como ``\\g<2>0``. " -"(``\\20`` seria interpretado como uma referência ao grupo de ``20``, e não " -"uma referência ao grupo ``2`` seguido pelo caractere literal ``0``). As " -"substituições a seguir são todas equivalentes, mas usam todas as três " -"variações da string de substituição. ::" - -#: ../../howto/regex.rst:1207 +"correspondente. ``\\g<2>`` é, portanto, equivalente a ``\\2``, mas não é " +"ambígua em uma string de substituição, tal como ``\\g<2>0``. (``\\20`` seria " +"interpretado como uma referência ao grupo de 20, e não uma referência ao " +"grupo 2 seguido pelo caractere literal ``'0'``). As substituições a seguir " +"são todas equivalentes, mas usam todas as três variações da string de " +"substituição. ::" + +#: ../../howto/regex.rst:1203 +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 "" +">>> 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}'" + +#: ../../howto/regex.rst:1211 msgid "" "*replacement* can also be a function, which gives you even more control. If " "*replacement* is a function, the function is called for every non-" @@ -2131,7 +2855,7 @@ msgstr "" "pode usar essas informações para calcular a string de substituição desejada " "e retorná-la." -#: ../../howto/regex.rst:1213 +#: ../../howto/regex.rst:1217 msgid "" "In the following example, the replacement function translates decimals into " "hexadecimal::" @@ -2139,7 +2863,27 @@ msgstr "" "No exemplo a seguir, a função de substituição traduz decimais em " "hexadecimal::" -#: ../../howto/regex.rst:1225 +#: ../../howto/regex.rst:1220 +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 "" +">>> 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.'" + +#: ../../howto/regex.rst:1229 msgid "" "When using the module-level :func:`re.sub` function, the pattern is passed " "as the first argument. The pattern may be provided as an object or as a " @@ -2155,11 +2899,11 @@ msgstr "" "usar modificadores embutidos na string padrão, por exemplo, ``sub(\"(?i)b+" "\", \"x\", \"bbbb BBBB\")`` retorna ``'x x'``." -#: ../../howto/regex.rst:1233 +#: ../../howto/regex.rst:1237 msgid "Common Problems" -msgstr "Problemas Comuns" +msgstr "Problemas comuns" -#: ../../howto/regex.rst:1235 +#: ../../howto/regex.rst:1239 msgid "" "Regular expressions are a powerful tool for some applications, but in some " "ways their behaviour isn't intuitive and at times they don't behave the way " @@ -2171,11 +2915,11 @@ msgstr "" "não se comportam da maneira que você espera que elas se comportem. Esta " "seção irá apontar algumas das armadilhas mais comuns." -#: ../../howto/regex.rst:1241 +#: ../../howto/regex.rst:1245 msgid "Use String Methods" -msgstr "Usando String Methods" +msgstr "Usando métodos de string" -#: ../../howto/regex.rst:1243 +#: ../../howto/regex.rst:1247 msgid "" "Sometimes using the :mod:`re` module is a mistake. If you're matching a " "fixed string, or a single character class, and you're not using any :mod:" @@ -2186,8 +2930,17 @@ 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 possuem 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 +#: ../../howto/regex.rst:1255 msgid "" "One example might be replacing a single fixed string with another one; for " "example, you might replace ``word`` with ``deed``. :func:`re.sub` seems " @@ -2199,8 +2952,17 @@ 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 delimitador de palavra em ambos os lados. Isso leva a " +"tarefa para além da capacidade de :meth:`!replace`.)" -#: ../../howto/regex.rst:1260 +#: ../../howto/regex.rst:1264 msgid "" "Another common task is deleting every occurrence of a single character from " "a string or replacing it with another single character. You might do this " @@ -2208,20 +2970,26 @@ 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 substituí-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 +#: ../../howto/regex.rst:1270 msgid "" "In short, before turning to the :mod:`re` module, consider whether your " "problem can be solved with a faster and simpler string method." msgstr "" "Em suma, antes de recorrer ao o módulo :mod:`re`, considere se o seu " -"problema pode ser resolvido com um método string mais rápido e mais simples." +"problema pode ser resolvido com um método de string mais rápido e mais " +"simples." -#: ../../howto/regex.rst:1271 +#: ../../howto/regex.rst:1275 msgid "match() versus search()" msgstr "match() versus search()" -#: ../../howto/regex.rst:1273 +#: ../../howto/regex.rst:1277 msgid "" "The :func:`~re.match` function only checks if the RE matches at the " "beginning of the string while :func:`~re.search` will scan forward through " @@ -2230,14 +2998,46 @@ 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 percorrendo a 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:1284 +#: ../../howto/regex.rst:1283 +msgid "" +">>> print(re.match('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.match('super', 'insuperable'))\n" +"None" +msgstr "" +">>> print(re.match('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.match('super', 'insuperable'))\n" +"None" + +#: ../../howto/regex.rst:1288 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:1291 +msgid "" +">>> print(re.search('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.search('super', 'insuperable').span())\n" +"(2, 7)" +msgstr "" +">>> print(re.search('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.search('super', 'insuperable').span())\n" +"(2, 7)" -#: ../../howto/regex.rst:1292 +#: ../../howto/regex.rst:1296 msgid "" "Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``." "*`` to the front of your RE. Resist this temptation and use :func:`re." @@ -2259,7 +3059,7 @@ msgstr "" "caractere inicial, apenas tentando a combinação completa se um ``'C'`` for " "encontrado." -#: ../../howto/regex.rst:1301 +#: ../../howto/regex.rst:1305 msgid "" "Adding ``.*`` defeats this optimization, requiring scanning to the end of " "the string and then backtracking to find a match for the rest of the RE. " @@ -2269,11 +3069,11 @@ msgstr "" "o final da string e, em seguida, retroceder para encontrar uma " "correspondência para o resto da RE. Use :func:`re.search` em vez disso." -#: ../../howto/regex.rst:1307 +#: ../../howto/regex.rst:1311 msgid "Greedy versus Non-Greedy" -msgstr "Gulosos versus não Gulosos" +msgstr "Gulosos versus não-gulosos" -#: ../../howto/regex.rst:1309 +#: ../../howto/regex.rst:1313 msgid "" "When repeating a regular expression, as in ``a*``, the resulting action is " "to consume as much of the pattern as possible. This fact often bites you " @@ -2288,7 +3088,25 @@ msgstr "" "para combinar uma única tag HTML não funciona por causa da natureza gulosa " "de ``.*``. ::" -#: ../../howto/regex.rst:1323 +#: ../../howto/regex.rst:1319 +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 "" +">>> s = 'Title'\n" +">>> len(s)\n" +"32\n" +">>> print(re.match('<.*>', s).span())\n" +"(0, 32)\n" +">>> print(re.match('<.*>', s).group())\n" +"Title" + +#: ../../howto/regex.rst:1327 msgid "" "The RE matches the ``'<'`` in ``''``, and the ``.*`` consumes the rest " "of the string. There's still more left in the RE, though, and the ``>`` " @@ -2297,8 +3115,14 @@ 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 correspondência final se estende do ``'<'`` em " +"``''`` ao ``'>'`` em ``''``, que não é o que você quer." -#: ../../howto/regex.rst:1330 +#: ../../howto/regex.rst:1334 msgid "" "In this case, the solution is to use the non-greedy quantifiers ``*?``, ``+?" "``, ``??``, or ``{m,n}?``, which match as *little* text as possible. In the " @@ -2306,8 +3130,22 @@ 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:1340 +msgid "" +">>> print(re.match('<.*?>', s).group())\n" +"" +msgstr "" +">>> print(re.match('<.*?>', s).group())\n" +"" -#: ../../howto/regex.rst:1339 +#: ../../howto/regex.rst:1343 msgid "" "(Note that parsing HTML or XML with regular expressions is painful. Quick-" "and-dirty patterns will handle common cases, but HTML and XML have special " @@ -2323,11 +3161,11 @@ msgstr "" "possíveis, se tornarão um padrão muito complicado. Use um módulo de análise " "de HTML ou XML para tais tarefas.)" -#: ../../howto/regex.rst:1347 +#: ../../howto/regex.rst:1351 msgid "Using re.VERBOSE" msgstr "Usando re.VERBOSE" -#: ../../howto/regex.rst:1349 +#: ../../howto/regex.rst:1353 msgid "" "By now you've probably noticed that regular expressions are a very compact " "notation, but they're not terribly readable. REs of moderate complexity can " @@ -2340,14 +3178,17 @@ msgstr "" "de barras invertidas, parênteses e metacaracteres, fazendo com que se tornem " "difíceis de ler e compreender." -#: ../../howto/regex.rst:1354 +#: ../../howto/regex.rst:1358 msgid "" "For such REs, specifying the :const:`re.VERBOSE` flag when compiling the " "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 +#: ../../howto/regex.rst:1362 msgid "" "The ``re.VERBOSE`` flag has several effects. Whitespace in the regular " "expression that *isn't* inside a character class is ignored. This means " @@ -2362,19 +3203,43 @@ msgstr "" "ignorado. Isto significa que uma expressão como ``dog | cat`` é equivalente " "ao menos legível ``dog|cat``, mas ``[a b]`` ainda vai coincidir com os " "caracteres ``a``, ``b``, ou um ``espaço``. Além disso, você também pode " -"colocar comentários dentro de uma RE; comentários se estendem de um " -"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:1375 +"colocar comentários dentro de uma RE, que se estendem de um 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:1370 +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 "" +"pat = re.compile(r\"\"\"\n" +" \\s* # Ignora espaços em branco no início\n" +" (?P
[^:]+) # Nome do cabeçalho\n" +" \\s* : # Espaço em branco e caractere de dois pontos\n" +" (?P.*?) # O valor do cabeçalho -- o *? costumava\n" +" # perder o seguinte espaço em branco ao final\n" +" \\s*$ # Espaço em branco no final até o fim da linha\n" +"\"\"\", re.VERBOSE)" + +#: ../../howto/regex.rst:1379 msgid "This is far more readable than::" msgstr "Isso é muito mais legível do que::" #: ../../howto/regex.rst:1381 +msgid "pat = re.compile(r\"\\s*(?P
[^:]+)\\s*:(?P.*?)\\s*$\")" +msgstr "pat = re.compile(r\"\\s*(?P
[^:]+)\\s*:(?P.*?)\\s*$\")" + +#: ../../howto/regex.rst:1385 msgid "Feedback" msgstr "Comentários" -#: ../../howto/regex.rst:1383 +#: ../../howto/regex.rst:1387 msgid "" "Regular expressions are a complicated topic. Did this document help you " "understand them? Were there parts that were unclear, or Problems you " @@ -2386,7 +3251,7 @@ msgstr "" "vivenciou que não foram abordadas aqui? Se assim for, por favor, envie " "sugestões de melhorias para o autor." -#: ../../howto/regex.rst:1388 +#: ../../howto/regex.rst:1392 msgid "" "The most complete book on regular expressions is almost certainly Jeffrey " "Friedl's Mastering Regular Expressions, published by O'Reilly. " @@ -2396,3 +3261,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..140016238 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..de242c895 100644 --- a/howto/sorting.po +++ b/howto/sorting.po @@ -1,34 +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 -# Lucas Sanches , 2021 -# Hildeberto Abreu Magalhães , 2022 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# Cezar Gabriel, 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-09-23 14:56+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Cezar Gabriel, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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" @@ -58,7 +56,7 @@ msgstr "" #: ../../howto/sorting.rst:17 msgid "Sorting Basics" -msgstr "Básico de Ordenação" +msgstr "Básico de ordenação" #: ../../howto/sorting.rst:19 msgid "" @@ -66,7 +64,15 @@ msgid "" "It returns a new sorted list:" msgstr "" "Uma ordenação ascendente simples é muito fácil: apenas chame a função :func:" -"`sorted`. Retorna uma nova lista ordenada:" +"`sorted`. Você terá como retorno 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 "" @@ -75,10 +81,23 @@ msgid "" "than :func:`sorted` - but if you don't need the original list, it's slightly " "more efficient." msgstr "" -"Você também pode utilizar o método :meth:`list.sort`. Isso modifica a lista " -"em si (e retorna ``None`` para evitar confusão). Usualmente este método é " -"menos conveniente que a função :func:`sorted` - mas se você não precisará da " -"lista original, esta maneira é levemente mais eficiente." +"Você também pode utilizar o método :meth:`list.sort`. Ele modificará a lista " +"localmente (e retornará ``None`` para evitar confusão). Usualmente este " +"método é menos conveniente que a função :func:`sorted` - mas, se a lista " +"original não for posteriormente útil, esta maneira será 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 "" @@ -88,9 +107,17 @@ 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" +msgstr "Funções chave" #: ../../howto/sorting.rst:50 msgid "" @@ -106,6 +133,15 @@ 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 "" +">>> sorted(\"Essa é uma string de teste do Andrew\".split(), key=str." +"casefold)\n" +"['Andrew', 'de', 'do', 'Essa', 'string', 'teste', 'uma', 'é']" + #: ../../howto/sorting.rst:61 msgid "" "The value of the *key* parameter should be a function (or other callable) " @@ -114,18 +150,36 @@ msgid "" "each input record." msgstr "" "O valor do parâmetro *key* deve ser uma função (ou outro chamável) que " -"recebe um único argumento e retorna uma chave à ser utilizada com o " -"propósito de ordenação. Esta técnica é rápida porque a função chave é " -"chamada exatamente uma vez para cada entrada de registro." +"recebe um único argumento e retorna uma chave à ser utilizada na ordenação. " +"Como a função chave é chamada exatamente uma vez para cada elemento, esta " +"técnica é rápida." #: ../../howto/sorting.rst:66 msgid "" "A common pattern is to sort complex objects using some of the object's " "indices as keys. For example:" msgstr "" -"Uma padrão comum é ordenar objetos complexos utilizando algum índice do " +"Um padrão comum é ordenar objetos complexos utilizando um dos índices 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 "" +">>> tuplas_alunos = [\n" +"... ('joão', 'A', 15),\n" +"... ('joana', 'B', 12),\n" +"... ('davi', 'B', 10),\n" +"... ]\n" +">>> sorted(tuplas_alunos, key=lambda aluno: aluno[2]) # ordena por idade\n" +"[('davi', 'B', 10), ('joana', 'B', 12), ('joão', 'A', 15)]" + #: ../../howto/sorting.rst:79 msgid "" "The same technique works for objects with named attributes. For example:" @@ -133,12 +187,51 @@ 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 "" +">>> class Aluno:\n" +"... def __init__(self, nome, nota, idade):\n" +"... self.nome = nome\n" +"... self.nota = nota\n" +"... self.idade = idade\n" +"... def __repr__(self):\n" +"... return repr((self.nome, self.nota, self.idade))\n" +"\n" +">>> objetos_alunos = [\n" +"... Aluno('john', 'A', 15),\n" +"... Aluno('jane', 'B', 12),\n" +"... Aluno('dave', 'B', 10),\n" +"... ]\n" +">>> sorted(objetos_alunos, key=lambda aluno: aluno.idade) # ordena por " +"idade\n" +"[('davi', 'B', 10), ('joana', 'B', 12), ('joão', 'A', 15)]" + #: ../../howto/sorting.rst:99 msgid "" "Objects with named attributes can be made by a regular class as shown above, " "or they can be instances of :class:`~dataclasses.dataclass` or a :term:" "`named tuple`." msgstr "" +"Objetos com atríbutos nomeados podem ser criados como uma classe padrão, " +"igual ao exemplo acima, podem ser instâncias de :class:`~dataclasses." +"dataclass` ou mesmo uma :term:`named tuple`." #: ../../howto/sorting.rst:104 msgid "Operator Module Functions and Partial Function Evaluation" @@ -151,6 +244,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 +255,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 +274,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 +291,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 +320,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 +343,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 +369,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 +386,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 +444,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 +511,7 @@ msgstr "" #: ../../howto/sorting.rst:253 msgid "Comparison Functions" -msgstr "" +msgstr "Funções de comparação" #: ../../howto/sorting.rst:255 msgid "" @@ -367,6 +543,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 +571,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 +621,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..fd126cdc8 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..a79c5033f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..e7a7f1e94 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,15 +556,69 @@ 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 "" ":attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary " -"of response codes in that shows all the response codes used by :rfc:`2616`. " -"The dictionary is reproduced here for convenience ::" +"of response codes that shows all the response codes used by :rfc:`2616`. An " +"excerpt from the dictionary is shown below ::" 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`. Um trecho do dicionário é mostrado abaixo ::" -#: ../../howto/urllib2.rst:319 +#: ../../howto/urllib2.rst:251 +msgid "" +"responses = {\n" +" ...\n" +" : ('OK', 'Request fulfilled, document follows'),\n" +" ...\n" +" : ('Forbidden',\n" +" 'Request forbidden -- authorization will " +"'\n" +" 'not help'),\n" +" : ('Not Found',\n" +" 'Nothing matches the given URI'),\n" +" ...\n" +" : (\"I'm a Teapot\",\n" +" 'Server refuses to brew coffee because " +"'\n" +" 'it is a teapot'),\n" +" ...\n" +" : ('Service Unavailable',\n" +" 'The server cannot process the " +"'\n" +" 'request due to a high load'),\n" +" ...\n" +" }" +msgstr "" +"responses = {\n" +" ...\n" +" : ('OK', 'Request fulfilled, document follows'),\n" +" ...\n" +" : ('Forbidden',\n" +" 'Request forbidden -- authorization will " +"'\n" +" 'not help'),\n" +" : ('Not Found',\n" +" 'Nothing matches the given URI'),\n" +" ...\n" +" : (\"I'm a Teapot\",\n" +" 'Server refuses to brew coffee because " +"'\n" +" 'it is a teapot'),\n" +" ...\n" +" : ('Service Unavailable',\n" +" 'The server cannot process the " +"'\n" +" 'request due to a high load'),\n" +" ...\n" +" }" + +#: ../../howto/urllib2.rst:271 msgid "" "When an error is raised the server responds by returning an HTTP error code " "*and* an error page. You can use the :exc:`~urllib.error.HTTPError` instance " @@ -352,71 +626,189 @@ 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:339 +#: ../../howto/urllib2.rst:276 +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:291 msgid "Wrapping it Up" -msgstr "" +msgstr "Resumindo" -#: ../../howto/urllib2.rst:341 +#: ../../howto/urllib2.rst:293 msgid "" "So if you want to be prepared for :exc:`~urllib.error.HTTPError` *or* :exc:" "`~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 +#: ../../howto/urllib2.rst:297 msgid "Number 1" -msgstr "" +msgstr "Número 1" -#: ../../howto/urllib2.rst:367 +#: ../../howto/urllib2.rst:302 +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:319 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 +#: ../../howto/urllib2.rst:323 msgid "Number 2" -msgstr "" +msgstr "Número 2" -#: ../../howto/urllib2.rst:392 +#: ../../howto/urllib2.rst:327 +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:344 msgid "info and geturl" -msgstr "" +msgstr "info e geturl" -#: ../../howto/urllib2.rst:394 +#: ../../howto/urllib2.rst:346 msgid "" "The response returned by urlopen (or the :exc:`~urllib.error.HTTPError` " "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 +#: ../../howto/urllib2.rst:350 msgid "" "**geturl** - this returns the real URL of the page fetched. This is useful " "because ``urlopen`` (or the opener object used) may have followed a " "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 +#: ../../howto/urllib2.rst:354 msgid "" "**info** - this returns a dictionary-like object that describes the page " "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 +#: ../../howto/urllib2.rst:358 msgid "" "Typical headers include 'Content-length', 'Content-type', and so on. See the " "`Quick Reference to HTTP Headers `_ for a " "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 +#: ../../howto/urllib2.rst:365 msgid "Openers and Handlers" -msgstr "" +msgstr "Abridores e tratadores" -#: ../../howto/urllib2.rst:415 +#: ../../howto/urllib2.rst:367 msgid "" "When you fetch a URL you use an opener (an instance of the perhaps " "confusingly named :class:`urllib.request.OpenerDirector`). Normally we have " @@ -426,53 +818,77 @@ 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 +#: ../../howto/urllib2.rst:375 msgid "" "You will want to create openers if you want to fetch URLs with specific " "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 +#: ../../howto/urllib2.rst:379 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 +#: ../../howto/urllib2.rst:382 msgid "" "Alternatively, you can use ``build_opener``, which is a convenience function " "for creating opener objects with a single function call. ``build_opener`` " "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 +#: ../../howto/urllib2.rst:387 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 +#: ../../howto/urllib2.rst:390 msgid "" "``install_opener`` can be used to make an ``opener`` object the (global) " "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 +#: ../../howto/urllib2.rst:394 msgid "" "Opener objects have an ``open`` method, which can be called directly to " "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 +#: ../../howto/urllib2.rst:400 msgid "Basic Authentication" -msgstr "" +msgstr "Autenticação básica" -#: ../../howto/urllib2.rst:450 +#: ../../howto/urllib2.rst:402 msgid "" "To illustrate creating and installing a handler we will use the " "``HTTPBasicAuthHandler``. For a more detailed discussion of this subject -- " @@ -480,28 +896,46 @@ msgid "" "Authentication Tutorial `__." msgstr "" +"Para ilustrar a criação e instalação de um manipulador, usaremos o " +"``HTTPBasicAuthHandler``. Para uma discussão mais detalhada sobre este " +"assunto — incluindo uma explicação de como funciona a autenticação básica — " +"consulte este `tutorial de autenticação básica `__." -#: ../../howto/urllib2.rst:456 +#: ../../howto/urllib2.rst:408 msgid "" "When authentication is required, the server sends a header (as well as the " "401 error code) requesting authentication. This specifies the " "authentication scheme and a 'realm'. The header looks like: ``WWW-" "Authenticate: SCHEME realm=\"REALM\"``." msgstr "" +"Quando a autenticação é necessária, o servidor envia um cabeçalho (e o " +"código de erro 401) solicitando autenticação. Isso especifica o esquema de " +"autenticação e um \"domínio\". O cabeçalho se parece com: ``WWW-" +"Authenticate: SCHEME realm=\"REALM\"``." -#: ../../howto/urllib2.rst:461 +#: ../../howto/urllib2.rst:413 msgid "e.g." -msgstr "" +msgstr "Por exemplo:" + +#: ../../howto/urllib2.rst:415 +msgid "WWW-Authenticate: Basic realm=\"cPanel Users\"" +msgstr "WWW-Authenticate: Basic realm=\"cPanel Users\"" -#: ../../howto/urllib2.rst:468 +#: ../../howto/urllib2.rst:420 msgid "" "The client should then retry the request with the appropriate name and " "password for the realm included as a header in the request. This is 'basic " "authentication'. In order to simplify this process we can create an instance " "of ``HTTPBasicAuthHandler`` and an opener to use this handler." msgstr "" +"O cliente deve então tentar a solicitação novamente com o nome e a senha " +"apropriados para o domínio incluídos como cabeçalho na solicitação. Isso é " +"\"autenticação básica\". Para simplificar esse processo, podemos criar uma " +"instância de ``HTTPBasicAuthHandler`` e um opener para usar esse manipulador." -#: ../../howto/urllib2.rst:473 +#: ../../howto/urllib2.rst:425 msgid "" "The ``HTTPBasicAuthHandler`` uses an object called a password manager to " "handle the mapping of URLs and realms to passwords and usernames. If you " @@ -513,14 +947,69 @@ msgid "" "providing an alternative combination for a specific realm. We indicate this " "by providing ``None`` as the realm argument to the ``add_password`` method." msgstr "" +"O ``HTTPBasicAuthHandler`` usa um objeto chamado gerenciador de senhas para " +"manipular o mapeamento de URLs e domínios para senhas e nomes de usuário. Se " +"você souber qual é o domínio (a partir do cabeçalho de autenticação enviado " +"pelo servidor), poderá usar um ``HTTPPasswordMgr``. Frequentemente, não " +"importa qual seja o domínio. Nesse caso, é conveniente usar " +"``HTTPPasswordMgrWithDefaultRealm``. Isso permite que você especifique um " +"nome de usuário e uma senha padrão para uma URL. Isso será fornecido caso " +"você não forneça uma combinação alternativa para um domínio específico. " +"Indicamos isso fornecendo ``None`` como argumento de domínio para o método " +"``add_password``." -#: ../../howto/urllib2.rst:483 +#: ../../howto/urllib2.rst:435 msgid "" "The top-level URL is the first URL that requires authentication. URLs " "\"deeper\" than the URL you pass to .add_password() will also match. ::" msgstr "" +"A URL de nível superior é a primeira URL que requer autenticação. URLs " +"\"mais profundas\" que a URL que você passa para .add_password() também " +"corresponderão. ::" -#: ../../howto/urllib2.rst:508 +#: ../../howto/urllib2.rst:438 +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 "" +"# cria um gerenciador de senhas\n" +"password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()\n" +"\n" +"# Adiciona o nome de usuário e senha.\n" +"# Se soubéssemos o realm, poderíamos usá-lo em vez de 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" +"# cria um \"opener\" (OpenerDirector instance)\n" +"opener = urllib.request.build_opener(handler)\n" +"\n" +"# usa o opener para obter uma URL\n" +"opener.open(a_url)\n" +"\n" +"# Instala o opener.\n" +"# Agora, todas as chamadas a urllib.request.urlopen usam nosso opener.\n" +"urllib.request.install_opener(opener)" + +#: ../../howto/urllib2.rst:460 msgid "" "In the above example we only supplied our ``HTTPBasicAuthHandler`` to " "``build_opener``. By default openers have the handlers for normal situations " @@ -529,8 +1018,15 @@ msgid "" "``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``, " "``FileHandler``, ``DataHandler``, ``HTTPErrorProcessor``." msgstr "" +"No exemplo acima, fornecemos apenas nosso ``HTTPBasicAuthHandler`` para " +"``build_opener``. Por padrão, os \"openers\" possuem os manipuladores para " +"situações normais: ``ProxyHandler`` (se uma configuração de proxy, como uma " +"variável de ambiente :envvar:`!http_proxy`, estiver definida), " +"``UnknownHandler``, ``HTTPHandler``, ``HTTPDefaultErrorHandler``, " +"``HTTPRedirectHandler``, ``FTPHandler``, ``FileHandler``, ``DataHandler``, " +"``HTTPErrorProcessor``." -#: ../../howto/urllib2.rst:515 +#: ../../howto/urllib2.rst:467 msgid "" "``top_level_url`` is in fact *either* a full URL (including the 'http:' " "scheme component and the hostname and optionally the port number) e.g. " @@ -540,12 +1036,20 @@ msgid "" "authority, if present, must NOT contain the \"userinfo\" component - for " "example ``\"joe:password@example.com\"`` is not correct." msgstr "" +"``top_level_url`` é, na verdade, *ou* uma URL completa (incluindo o " +"componente do esquema 'http:', o nome do host e, opcionalmente, o número da " +"porta), por exemplo, ``\"http://example.com/\"``, *ou* uma " +"\"autoridade\" (ou seja, o nome do host, incluindo, opcionalmente, o número " +"da porta), por exemplo, ``\"example.com\"`` ou ``\"example.com:8080\"`` " +"(este último exemplo inclui um número de porta). A autoridade, se presente, " +"NÃO deve conter o componente \"userinfo\" - por exemplo, ``\"joe:" +"senha@example.com\"`` não está correto." -#: ../../howto/urllib2.rst:525 +#: ../../howto/urllib2.rst:477 msgid "Proxies" msgstr "Proxies" -#: ../../howto/urllib2.rst:527 +#: ../../howto/urllib2.rst:479 msgid "" "**urllib** will auto-detect your proxy settings and use those. This is " "through the ``ProxyHandler``, which is part of the normal handler chain when " @@ -554,31 +1058,55 @@ msgid "" "our own ``ProxyHandler``, with no proxies defined. This is done using " "similar steps to setting up a `Basic Authentication`_ handler: ::" msgstr "" +"**urllib** detectará automaticamente suas configurações de proxy e as " +"utilizará. Isso ocorre por meio do ``ProxyHandler``, que faz parte da cadeia " +"de manipuladores normal quando uma configuração de proxy é detectada. " +"Normalmente, isso é bom, mas há ocasiões em que pode não ser útil [#]_. Uma " +"maneira de fazer isso é configurar nosso próprio ``ProxyHandler``, sem " +"proxies definidos. Isso é feito seguindo etapas semelhantes à configuração " +"de um manipulador de `autenticação básica`_: ::" -#: ../../howto/urllib2.rst:540 +#: ../../howto/urllib2.rst:486 +msgid "" +">>> proxy_support = urllib.request.ProxyHandler({})\n" +">>> opener = urllib.request.build_opener(proxy_support)\n" +">>> urllib.request.install_opener(opener)" +msgstr "" +">>> proxy_support = urllib.request.ProxyHandler({})\n" +">>> opener = urllib.request.build_opener(proxy_support)\n" +">>> urllib.request.install_opener(opener)" + +#: ../../howto/urllib2.rst:492 msgid "" "Currently ``urllib.request`` *does not* support fetching of ``https`` " "locations through a proxy. However, this can be enabled by extending urllib." "request as shown in the recipe [#]_." msgstr "" +"Atualmente, ``urllib.request`` *não* oferece suporte à busca de locais " +"``https`` por meio de um proxy. No entanto, isso pode ser habilitado " +"estendendo urllib.request, conforme mostrado na receita [#]_." -#: ../../howto/urllib2.rst:546 +#: ../../howto/urllib2.rst:498 msgid "" "``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see " "the documentation on :func:`~urllib.request.getproxies`." msgstr "" +"``HTTP_PROXY`` será ignorado se uma variável ``REQUEST_METHOD`` estiver " +"definida; veja a documentação em :func:`~urllib.request.getproxies`." -#: ../../howto/urllib2.rst:551 +#: ../../howto/urllib2.rst:503 msgid "Sockets and Layers" -msgstr "" +msgstr "Socekts e camadas" -#: ../../howto/urllib2.rst:553 +#: ../../howto/urllib2.rst:505 msgid "" "The Python support for fetching resources from the web is layered. urllib " "uses the :mod:`http.client` library, which in turn uses the socket library." msgstr "" +"O suporte do Python para buscar recursos web é em camadas. urllib usa a " +"biblioteca :mod:`http.client`, que por sua vez usa a biblioteca de sockets." -#: ../../howto/urllib2.rst:556 +#: ../../howto/urllib2.rst:508 msgid "" "As of Python 2.3 you can specify how long a socket should wait for a " "response before timing out. This can be useful in applications which have to " @@ -587,49 +1115,96 @@ msgid "" "request levels. However, you can set the default timeout globally for all " "sockets using ::" msgstr "" +"A partir do Python 2.3, você pode especificar quanto tempo um soquete deve " +"aguardar por uma resposta antes de atingir o tempo limite. Isso pode ser " +"útil em aplicações que precisam buscar páginas web. Por padrão, o módulo " +"socket *não tem tempo limite* e pode travar. Atualmente, o tempo limite do " +"soquete não é exposto nos níveis http.client ou urllib.request. No entanto, " +"você pode definir o tempo limite padrão globalmente para todos os soquetes " +"usando ::" -#: ../../howto/urllib2.rst:579 +#: ../../howto/urllib2.rst:514 +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 "" +"import socket\n" +"import urllib.request\n" +"\n" +"# tempo limite em secungos\n" +"timeout = 10\n" +"socket.setdefaulttimeout(timeout)\n" +"\n" +"# isso chamada a urllib.request.urlopen agora usa o tempo limite padrão\n" +"# que nós definidos no módulo socket\n" +"req = urllib.request.Request('http://www.voidspace.org.uk')\n" +"response = urllib.request.urlopen(req)" + +#: ../../howto/urllib2.rst:531 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../howto/urllib2.rst:581 +#: ../../howto/urllib2.rst:533 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 +#: ../../howto/urllib2.rst:535 msgid "Google for example." msgstr "Google, por exemplo." -#: ../../howto/urllib2.rst:584 +#: ../../howto/urllib2.rst:536 msgid "" "Browser sniffing is a very bad practice for website design - building sites " "using web standards is much more sensible. Unfortunately a lot of sites " "still send different versions to different browsers." msgstr "" +"A detecção de navegadores é uma prática muito ruim para o design de sites; " +"construir sites usando padrões web é muito mais sensato. Infelizmente, " +"muitos sites ainda enviam versões diferentes para navegadores diferentes." -#: ../../howto/urllib2.rst:587 +#: ../../howto/urllib2.rst:539 msgid "" "The user agent for MSIE 6 is *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT " "5.1; SV1; .NET CLR 1.1.4322)'*" msgstr "" +"O user agent para MSIE 6 é *'Mozilla/4.0 (compatível; MSIE 6.0; Windows NT " +"5.1; SV1; .NET CLR 1.1.4322)'*" -#: ../../howto/urllib2.rst:589 +#: ../../howto/urllib2.rst:541 msgid "" "For details of more HTTP request headers, see `Quick Reference to HTTP " "Headers`_." msgstr "" +"Para obter detalhes sobre mais cabeçalhos de solicitação HTTP, consulte " +"`Referência rápida para cabeçalhos HTTP`_." -#: ../../howto/urllib2.rst:591 +#: ../../howto/urllib2.rst:543 msgid "" "In my case I have to use a proxy to access the internet at work. If you " "attempt to fetch *localhost* URLs through this proxy it blocks them. IE is " "set to use the proxy, which urllib picks up on. In order to test scripts " "with a localhost server, I have to prevent urllib from using the proxy." msgstr "" +"No meu caso, preciso usar um proxy para acessar a internet no trabalho. Se " +"você tentar buscar URLs *localhost* por meio desse proxy, ele as bloqueia. O " +"IE está configurado para usar o proxy, que o urllib detecta. Para testar " +"scripts com um servidor localhost, preciso impedir que o urllib use o proxy." -#: ../../howto/urllib2.rst:596 +#: ../../howto/urllib2.rst:548 msgid "" "urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe `_." msgstr "" +"Abridor urllib para proxy SSL (método CONNECT): `Receita do livro de " +"receitas ASPN `_." diff --git a/installing/index.po b/installing/index.po index 5482290bf..36b44f70a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,152 +103,124 @@ msgstr "" "Desde a sua introdução no Python 2.1, os seguintes recursos encontraram o " "caminho para o idioma usando esse mecanismo:" -#: ../../library/__future__.rst:41 +#: ../../library/__future__.rst:45 msgid "feature" msgstr "característica" -#: ../../library/__future__.rst:41 +#: ../../library/__future__.rst:46 msgid "optional in" msgstr "opcional em" -#: ../../library/__future__.rst:41 +#: ../../library/__future__.rst:47 msgid "mandatory in" msgstr "obrigatório em" -#: ../../library/__future__.rst:41 +#: ../../library/__future__.rst:48 msgid "effect" msgstr "efeito" -#: ../../library/__future__.rst:43 -msgid "nested_scopes" -msgstr "nested_scopes" - -#: ../../library/__future__.rst:43 +#: ../../library/__future__.rst:50 msgid "2.1.0b1" msgstr "2.1.0b1" -#: ../../library/__future__.rst:43 +#: ../../library/__future__.rst:51 msgid "2.2" msgstr "2.2" -#: ../../library/__future__.rst:43 +#: ../../library/__future__.rst:52 msgid ":pep:`227`: *Statically Nested Scopes*" msgstr ":pep:`227`: *Statically Nested Scopes*" -#: ../../library/__future__.rst:46 -msgid "generators" -msgstr "generators" - -#: ../../library/__future__.rst:46 +#: ../../library/__future__.rst:54 msgid "2.2.0a1" msgstr "2.2.0a1" -#: ../../library/__future__.rst:46 +#: ../../library/__future__.rst:55 msgid "2.3" msgstr "2.3" -#: ../../library/__future__.rst:46 +#: ../../library/__future__.rst:56 msgid ":pep:`255`: *Simple Generators*" msgstr ":pep:`255`: *Simple Generators*" -#: ../../library/__future__.rst:49 -msgid "division" -msgstr "division" - -#: ../../library/__future__.rst:49 +#: ../../library/__future__.rst:58 msgid "2.2.0a2" msgstr "2.2.0a2" -#: ../../library/__future__.rst:49 ../../library/__future__.rst:52 -#: ../../library/__future__.rst:58 ../../library/__future__.rst:61 +#: ../../library/__future__.rst:59 ../../library/__future__.rst:63 +#: ../../library/__future__.rst:71 ../../library/__future__.rst:75 msgid "3.0" msgstr "3.0" -#: ../../library/__future__.rst:49 +#: ../../library/__future__.rst:60 msgid ":pep:`238`: *Changing the Division Operator*" msgstr ":pep:`238`: *Changing the Division Operator*" -#: ../../library/__future__.rst:52 -msgid "absolute_import" -msgstr "absolute_import" - -#: ../../library/__future__.rst:52 ../../library/__future__.rst:55 +#: ../../library/__future__.rst:62 ../../library/__future__.rst:66 msgid "2.5.0a1" msgstr "2.5.0a1" -#: ../../library/__future__.rst:52 +#: ../../library/__future__.rst:64 msgid ":pep:`328`: *Imports: Multi-Line and Absolute/Relative*" msgstr ":pep: `328`: *Imports: Multi-Line e Absolute/Relative*" -#: ../../library/__future__.rst:55 -msgid "with_statement" -msgstr "with_statement" - -#: ../../library/__future__.rst:55 +#: ../../library/__future__.rst:67 msgid "2.6" msgstr "2.6" -#: ../../library/__future__.rst:55 -msgid ":pep:`343`: *The \"with\" Statement*" -msgstr ":pep:`343`: *The \"with\" Statement*" - -#: ../../library/__future__.rst:58 -msgid "print_function" -msgstr "print_function" +#: ../../library/__future__.rst:68 +msgid ":pep:`343`: *The “with” Statement*" +msgstr ":pep:`343`: *The “with” Statement*" -#: ../../library/__future__.rst:58 ../../library/__future__.rst:61 +#: ../../library/__future__.rst:70 ../../library/__future__.rst:74 msgid "2.6.0a2" msgstr "2.6.0a2" -#: ../../library/__future__.rst:58 +#: ../../library/__future__.rst:72 msgid ":pep:`3105`: *Make print a function*" msgstr ":pep:`3105`: *Make print a function*" -#: ../../library/__future__.rst:61 -msgid "unicode_literals" -msgstr "unicode_literals" - -#: ../../library/__future__.rst:61 +#: ../../library/__future__.rst:76 msgid ":pep:`3112`: *Bytes literals in Python 3000*" msgstr ":pep:`3112`: *Bytes literals in Python 3000*" -#: ../../library/__future__.rst:64 -msgid "generator_stop" -msgstr "generator_stop" - -#: ../../library/__future__.rst:64 +#: ../../library/__future__.rst:78 msgid "3.5.0b1" msgstr "3.5.0b1" -#: ../../library/__future__.rst:64 +#: ../../library/__future__.rst:79 msgid "3.7" msgstr "3.7" -#: ../../library/__future__.rst:64 +#: ../../library/__future__.rst:80 msgid ":pep:`479`: *StopIteration handling inside generators*" msgstr ":pep:`479`: *StopIteration handling inside generators*" -#: ../../library/__future__.rst:67 -msgid "annotations" -msgstr "annotations" - -#: ../../library/__future__.rst:67 +#: ../../library/__future__.rst:82 msgid "3.7.0b1" msgstr "3.7.0b1" -#: ../../library/__future__.rst:67 -msgid "TBD [1]_" -msgstr "Para ser feito [1]_" +#: ../../library/__future__.rst:83 +msgid "Never [1]_" +msgstr "Nunca [1]_" -#: ../../library/__future__.rst:67 +#: ../../library/__future__.rst:84 msgid ":pep:`563`: *Postponed evaluation of annotations*" msgstr ":pep:`563`: *Postponed evaluation of annotations*" -#: ../../library/__future__.rst:77 +#: ../../library/__future__.rst:92 msgid "Each statement in :file:`__future__.py` is of the form::" msgstr "Cada instrução em :file:`__future__.py` é da forma::" -#: ../../library/__future__.rst:82 +#: ../../library/__future__.rst:94 +msgid "" +"FeatureName = _Feature(OptionalRelease, MandatoryRelease,\n" +" CompilerFlag)" +msgstr "" +"FeatureName = _Feature(OptionalRelease, MandatoryRelease,\n" +" CompilerFlag)" + +#: ../../library/__future__.rst:97 msgid "" "where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both " "are 5-tuples of the same form as :data:`sys.version_info`::" @@ -258,7 +228,25 @@ 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:94 +#: ../../library/__future__.rst:100 +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:109 msgid "" "*OptionalRelease* records the first release in which the feature was " "accepted." @@ -266,7 +254,7 @@ msgstr "" "*OptionalRelease* registra o primeiro lançamento no qual o recurso foi " "aceito." -#: ../../library/__future__.rst:98 +#: ../../library/__future__.rst:113 msgid "" "In the case of a *MandatoryRelease* that has not yet occurred, " "*MandatoryRelease* predicts the release in which the feature will become " @@ -275,7 +263,7 @@ msgstr "" "No caso de um *MandatoryRelease* que ainda não ocorreu, *MandatoryRelease* " "prevê o lançamento em que o recurso se tornará parte da linguagem." -#: ../../library/__future__.rst:102 +#: ../../library/__future__.rst:117 msgid "" "Else *MandatoryRelease* records when the feature became part of the " "language; in releases at or after that, modules no longer need a future " @@ -287,7 +275,7 @@ msgstr "" "instrução future para usar o recurso em questão, mas podem continuar a usar " "essas importações." -#: ../../library/__future__.rst:106 +#: ../../library/__future__.rst:121 msgid "" "*MandatoryRelease* may also be ``None``, meaning that a planned feature got " "dropped or that it is not yet decided." @@ -295,7 +283,7 @@ msgstr "" "*MandatoryRelease* também pode ser ``None``, o que significa que uma " "característica planejada foi descartada ou que isso ainda não está decidido." -#: ../../library/__future__.rst:111 +#: ../../library/__future__.rst:126 msgid "" "*CompilerFlag* is the (bitfield) flag that should be passed in the fourth " "argument to the built-in function :func:`compile` to enable the feature in " @@ -307,7 +295,7 @@ msgstr "" "código compilado dinamicamente. Este sinalizador é armazenado no atributo :" "attr:`_Feature.compiler_flag` em instâncias de :class:`_Feature`." -#: ../../library/__future__.rst:117 +#: ../../library/__future__.rst:132 msgid "" "``from __future__ import annotations`` was previously scheduled to become " "mandatory in Python 3.10, but the Python Steering Council twice decided to " @@ -326,18 +314,18 @@ msgstr "" "VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/>`__). Nenhuma decisão final foi tomada " "ainda. Veja também :pep:`563` e :pep:`649`." -#: ../../library/__future__.rst:127 +#: ../../library/__future__.rst:142 msgid ":ref:`future`" msgstr ":ref:`future`" -#: ../../library/__future__.rst:128 +#: ../../library/__future__.rst:143 msgid "How the compiler treats future imports." msgstr "Como o compilador trata as importações de future." -#: ../../library/__future__.rst:130 +#: ../../library/__future__.rst:145 msgid ":pep:`236` - Back to the __future__" msgstr ":pep:`236` - De volta ao __future__" -#: ../../library/__future__.rst:131 +#: ../../library/__future__.rst:146 msgid "The original proposal for the __future__ mechanism." msgstr "A proposta original para o mecanismo do __future__." diff --git a/library/__main__.po b/library/__main__.po index bd0b7434e..4366b2f2a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..3749f4977 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..2ca405c4c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..d6292a79a --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..e5f8f7068 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..3060e3dc0 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..020abf701 100644 --- a/library/argparse.po +++ b/library/argparse.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: -# 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +36,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 o :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 suas aplicações 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 +73,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 " @@ -98,9 +121,21 @@ msgid "" msgstr "" "O método :meth:`ArgumentParser.add_argument` anexa especificações de " "argumentos individuais ao analisador. Ele oferece suporte a argumentos " -"posicionais, opções que aceitam valores e sinalizadores liga/desliga::" +"posicionais, opções que aceitam valores e sinalizadores de ligar/desligar::" + +#: ../../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:50 +#: ../../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 +143,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'``" +"args = parser.parse_args()\n" +"print(args.filename, args.count, args.verbose)" 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" -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 +175,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 +188,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 +209,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 +221,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 +229,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 +244,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 +259,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 +279,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:616 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` calculates the name of the program to " +"display in help messages depending on the way the Python interpreter was run:" +msgstr "" +"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:140 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::" +"The :func:`base name ` of ``sys.argv[0]`` if a file was " +"passed as argument." 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::" +"O :func:`nome base ` de ``sys.argv[0]`` se um arquivo foi " +"passado como argumento." -#: ../../library/argparse.rst:263 +#: ../../library/argparse.rst:142 msgid "" -"The help for this program will display ``myprogram.py`` as the program name " -"(regardless of where the program was invoked from):" +"The Python interpreter name followed by ``sys.argv[0]`` if a directory or a " +"zipfile 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 nome do interpretador Python seguido por ``sys.argv[0]`` se um diretório " +"ou um arquivo zip foi passado como argumento." -#: ../../library/argparse.rst:282 +#: ../../library/argparse.rst:144 msgid "" -"To change this default behavior, another value can be supplied using the " -"``prog=`` argument to :class:`ArgumentParser`::" +"The Python interpreter name followed by ``-m`` followed by the module or " +"package name if the :option:`-m` option was used." 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 ``-m`` seguido pelo nome do " +"módulo ou pacote se a opção :option:`-m` foi usada." -#: ../../library/argparse.rst:292 +#: ../../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 +363,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 +435,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 +462,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 +476,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 +514,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 +536,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 +574,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 +584,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 +598,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 +610,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" +"esta descrição foi indentada de forma estranha, mas está tudo bem\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 +663,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 +721,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 +729,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 +771,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: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:551 +#: ../../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 +844,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,23 +864,52 @@ 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 :" +"Arguments read from a file must be one per line by default (but see also :" "meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they " "were in the same place as the original file referencing argument on the " "command line. So in the example above, the expression ``['-f', 'foo', " "'@args.txt']`` is considered equivalent to the expression ``['-f', 'foo', '-" "f', 'bar']``." msgstr "" -"Os argumentos lidos de um arquivo devem, por padrão, ser um por linha (mas " +"Por padrão, os argumentos lidos de um arquivo devem ser um por linha (mas " "veja também :meth:`~ArgumentParser.convert_arg_line_to_args`) e são tratados " -"como se estivessem no mesmo lugar que o argumento de referência do arquivo " -"original na linha de comando. Portanto, no exemplo acima, a expressão ``['-" -"f', 'foo', '@args.txt']`` é considerada equivalente à expressão ``['-f', " -"'foo', '-f', 'bar']``." +"como se estivessem no mesmo lugar que o argumento original que faz " +"referência ao arquivo na linha de comando. Portanto, no exemplo acima, a " +"expressão ``['-f', 'foo', '@args.txt']`` é considerada equivalente à " +"expressão ``['-f', 'foo', '-f', 'bar']``." + +#: ../../library/argparse.rst:426 +msgid "" +"Empty lines are treated as empty strings (``''``), which are allowed as " +"values but not as arguments. Empty lines that are read as arguments will " +"result in an \"unrecognized arguments\" error." +msgstr "" +"Linhas vazias são tratadas como strings vazias (``''``), que são permitidas " +"como valores, mas não como argumentos. Linhas vazias lidas como argumentos " +"resultarão em um erro de \"unrecognized arguments\" (\"argumentos não " +"reconhecidos\")." -#: ../../library/argparse.rst:580 +#: ../../library/argparse.rst:430 msgid "" ":class:`ArgumentParser` uses :term:`filesystem encoding and error handler` " "to read the file containing arguments." @@ -788,7 +917,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:433 msgid "" "The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that " "arguments will never be treated as file references." @@ -797,13 +926,13 @@ msgstr "" "significando que os argumentos nunca serão tratados como referências de " "arquivo." -#: ../../library/argparse.rst:586 +#: ../../library/argparse.rst:436 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 +941,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:444 msgid "argument_default" msgstr "argument_default" -#: ../../library/argparse.rst:596 +#: ../../library/argparse.rst:446 msgid "" "Generally, argument defaults are specified either by passing a default to :" "meth:`~ArgumentParser.add_argument` or by calling the :meth:`~ArgumentParser." @@ -836,11 +965,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:455 +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:466 msgid "allow_abbrev" msgstr "allow_abbrev" -#: ../../library/argparse.rst:618 +#: ../../library/argparse.rst:468 msgid "" "Normally, when you pass an argument list to the :meth:`~ArgumentParser." "parse_args` method of an :class:`ArgumentParser`, it :ref:`recognizes " @@ -850,17 +997,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:472 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:474 +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:485 msgid "conflict_handler" msgstr "conflict_handler" -#: ../../library/argparse.rst:637 +#: ../../library/argparse.rst:487 msgid "" ":class:`ArgumentParser` objects do not allow two actions with the same " "option string. By default, :class:`ArgumentParser` objects raise an " @@ -872,7 +1035,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:492 +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:499 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 +1063,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:504 +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:515 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 +1101,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:522 msgid "add_help" msgstr "add_help" -#: ../../library/argparse.rst:674 +#: ../../library/argparse.rst:524 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:528 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 +1126,25 @@ msgstr "" "pode ser feito passando ``False`` como o argumento ``add_help=`` para a " "classe :class:`ArgumentParser`::" -#: ../../library/argparse.rst:707 +#: ../../library/argparse.rst:532 +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:540 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 +1156,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:546 +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:555 msgid "exit_on_error" msgstr "exit_on_error" -#: ../../library/argparse.rst:724 +#: ../../library/argparse.rst:557 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:561 msgid "" "If the user would like to catch errors manually, the feature can be enabled " "by setting ``exit_on_error`` to ``False``::" @@ -962,11 +1195,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:564 +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:578 msgid "The add_argument() method" msgstr "O método add_argument()" -#: ../../library/argparse.rst:750 +#: ../../library/argparse.rst:584 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 +1234,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:587 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:590 msgid "" "action_ - The basic type of action to be taken when this argument is " "encountered at the command line." @@ -991,18 +1250,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:593 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:595 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:597 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 +1269,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:600 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:602 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:604 msgid "" "required_ - Whether or not the command-line option may be omitted (optionals " "only)." @@ -1029,15 +1288,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:607 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:609 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:611 msgid "" "dest_ - The name of the attribute to be added to the object returned by :" "meth:`parse_args`." @@ -1045,15 +1304,15 @@ msgstr "" "dest_ - O nome do atributo a ser adicionado ao objeto retornado por :meth:" "`parse_args`." -#: ../../library/argparse.rst:780 +#: ../../library/argparse.rst:614 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:622 msgid "name or flags" msgstr "name ou flags" -#: ../../library/argparse.rst:790 +#: ../../library/argparse.rst:624 msgid "" "The :meth:`~ArgumentParser.add_argument` method must know whether an " "optional argument, like ``-f`` or ``--foo``, or a positional argument, like " @@ -1063,19 +1322,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:630 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:632 +msgid ">>> parser.add_argument('-f', '--foo')" +msgstr ">>> parser.add_argument('-f', '--foo')" + +#: ../../library/argparse.rst:634 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:636 +msgid ">>> parser.add_argument('bar')" +msgstr ">>> parser.add_argument('bar')" + +#: ../../library/argparse.rst:638 msgid "" "When :meth:`~ArgumentParser.parse_args` is called, optional arguments will " "be identified by the ``-`` prefix, and the remaining arguments will be " @@ -1085,11 +1352,35 @@ msgstr "" "serão identificados pelo prefixo ``-``, e os argumentos restantes serão " "considerados posicionais::" -#: ../../library/argparse.rst:823 +#: ../../library/argparse.rst:642 +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:657 msgid "action" -msgstr "action" +msgstr "ação" -#: ../../library/argparse.rst:825 +#: ../../library/argparse.rst:659 msgid "" ":class:`ArgumentParser` objects associate command-line arguments with " "actions. These actions can do just about anything with the command-line " @@ -1106,15 +1397,15 @@ msgstr "" "os argumentos da linha de comando devem ser tratados. As ações fornecidas " "são:" -#: ../../library/argparse.rst:831 +#: ../../library/argparse.rst:665 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:668 msgid "" "``'store_const'`` - This stores the value specified by the const_ keyword " "argument; note that the const_ keyword argument defaults to ``None``. The " @@ -1126,33 +1417,73 @@ 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:673 +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:678 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:683 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 " -"default value is non-empty, the default elements will be present in the " -"parsed value for the option, with any values from the command line appended " -"after those default values. Example usage::" +">>> 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 "" -"``'append'`` - Isso armazena uma lista e anexa cada valor de argumento à " -"lista. É útil permitir que uma opção seja especificada várias vezes. Se o " -"valor padrão não estiver vazio, os elementos padrão estarão presentes no " -"valor analisado da opção, com quaisquer valores da linha de comando anexados " -"após esses valores padrão. Exemplo de uso::" +">>> 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:872 +#: ../../library/argparse.rst:690 +msgid "" +"``'append'`` - This appends each argument value to a list. It is useful for " +"allowing an option to be specified multiple times. If the default value is a " +"non-empty list, the parsed value will start with the default list's elements " +"and any values from the command line will be appended after those default " +"values. Example usage::" +msgstr "" +"``'append'`` - Isso anexa cada valor de argumento a uma lista. É útil " +"permitir para permitir que uma opção seja especificada várias vezes. Se o " +"valor padrão for uma lista não-vazia, o valor analisado vai iniciar com os " +"elementos padrão da lista e quaisquer valores da linha de comando serão " +"anexados após os valores padrão. Exemplo de uso::" + +#: ../../library/argparse.rst:696 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='append', default=['0'])\n" +">>> parser.parse_args('--foo 1 --foo 2'.split())\n" +"Namespace(foo=['0', '1', '2'])" +msgstr "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='append', default=['0'])\n" +">>> parser.parse_args('--foo 1 --foo 2'.split())\n" +"Namespace(foo=['0', '1', '2'])" + +#: ../../library/argparse.rst:701 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 +1497,55 @@ msgstr "" "útil quando vários argumentos precisam armazenar constantes na mesma lista. " "Por exemplo::" -#: ../../library/argparse.rst:884 +#: ../../library/argparse.rst:707 +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:713 +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:721 +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:728 msgid "" "``'count'`` - This counts the number of times a keyword argument occurs. For " "example, this is useful for increasing verbosity levels::" @@ -1174,13 +1553,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:731 +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:736 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:738 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 +1583,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:743 msgid "" "``'version'`` - This expects a ``version=`` keyword argument in the :meth:" "`~ArgumentParser.add_argument` call, and prints version information and " @@ -1202,62 +1593,116 @@ msgstr "" "meth:`~ArgumentParser.add_argument` e imprime informações de versão e sai " "quando invocado::" -#: ../../library/argparse.rst:909 +#: ../../library/argparse.rst:747 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:753 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 " -"boolean actions such as ``--foo`` and ``--no-foo``::" +"You may also specify an arbitrary action by passing an :class:`Action` " +"subclass (e.g. :class:`BooleanOptionalAction`) or other object that " +"implements the same interface. Only actions that consume command-line " +"arguments (e.g. ``'store'``, ``'append'``, ``'extend'``, or custom actions " +"with non-zero ``nargs``) can be used with positional arguments." 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` (por exemplo, :class:`BooleanOptionalAction`) ou outro objeto " +"que implemente a mesma interface. Somente ações que consomem argumentos de " +"linha de comando (por exemplo, ``'store'``, ``'append'``, ``'extend'`` ou " +"ações personalizadas com ``nargs`` diferentes de zero) podem ser usadas com " +"argumentos posicionais." -#: ../../library/argparse.rst:933 +#: ../../library/argparse.rst:759 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:764 msgid "An example of a custom action::" msgstr "Um exemplo de uma ação personalizada::" -#: ../../library/argparse.rst:957 +#: ../../library/argparse.rst:766 +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:784 msgid "For more details, see :class:`Action`." msgstr "Para mais detalhes, veja :class:`Action`." -#: ../../library/argparse.rst:963 +#: ../../library/argparse.rst:790 msgid "nargs" msgstr "nargs" -#: ../../library/argparse.rst:965 +#: ../../library/argparse.rst:792 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:797 msgid "" "``N`` (an integer). ``N`` arguments from the command line will be gathered " "together into a list. For example::" @@ -1265,7 +1710,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:800 +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:806 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 +1732,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:811 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 +1748,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:818 +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:828 msgid "" "One of the more common uses of ``nargs='?'`` is to allow optional input and " "output files::" @@ -1297,7 +1778,33 @@ msgstr "" "Um dos usos mais comuns de ``nargs='?'`` é permitir arquivos de entrada e " "saída opcionais::" -#: ../../library/argparse.rst:1018 +#: ../../library/argparse.rst:831 +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:845 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,34 +1816,70 @@ 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:850 +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:859 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 " -"least one command-line argument present. For example::" +"``'+'``. Just like ``'*'``, all command-line arguments present are gathered " +"into a list. Additionally, an error message will be generated if there " +"wasn't at least one command-line argument present. For example::" msgstr "" "``'+'``. Assim como ``'*'``, todos os argumentos de linha de comando " "presentes são reunidos em uma lista. Além disso, uma mensagem de erro será " "gerada se não houver pelo menos um argumento de linha de comando presente. " "Por exemplo::" -#: ../../library/argparse.rst:1044 +#: ../../library/argparse.rst:863 +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:871 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:881 msgid "const" msgstr "const" -#: ../../library/argparse.rst:1054 +#: ../../library/argparse.rst:883 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 +1891,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:887 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with " "``action='store_const'`` or ``action='append_const'``. These actions add " @@ -1364,23 +1907,23 @@ 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:895 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with option strings " "(like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional " "argument that can be followed by zero or one command-line arguments. When " "parsing the command line, if the option string is encountered with no " -"command-line argument following it, the value of ``const`` will be assumed " -"to be ``None`` instead. See the nargs_ description for examples." +"command-line argument following it, the value from ``const`` will be used. " +"See the nargs_ description for examples." msgstr "" "Quando :meth:`~ArgumentParser.add_argument` é chamado com strings de opções " "(como ``-f`` ou ``--foo``) e ``nargs='?'``. Isso cria um argumento opcional " "que pode ser seguido por zero ou um argumento de linha de comando. Ao " "analisar a linha de comando, se a string de opções for encontrada sem nenhum " -"argumento de linha de comando seguindo, o valor de ``const`` será presumido " -"como sendo ``None``. Veja a descrição de nargs_ para exemplos." +"argumento de linha de comando seguindo, o valor de ``const`` será usado. " +"Veja a descrição de nargs_ para exemplos." -#: ../../library/argparse.rst:1073 +#: ../../library/argparse.rst:902 msgid "" "``const=None`` by default, including when ``action='append_const'`` or " "``action='store_const'``." @@ -1388,11 +1931,11 @@ msgstr "" "``const=None`` por padrão, incluindo quando ``action='append_const'`` ou " "``action='store_const'``." -#: ../../library/argparse.rst:1080 +#: ../../library/argparse.rst:909 msgid "default" msgstr "default" -#: ../../library/argparse.rst:1082 +#: ../../library/argparse.rst:911 msgid "" "All optional arguments and some positional arguments may be omitted at the " "command line. The ``default`` keyword argument of :meth:`~ArgumentParser." @@ -1408,15 +1951,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:918 +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:925 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:928 +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:933 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 +2000,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:938 +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:944 msgid "" "For positional arguments with nargs_ equal to ``?`` or ``*``, the " "``default`` value is used when no command-line argument was present::" @@ -1438,7 +2023,34 @@ msgstr "" "``default`` é usado quando nenhum argumento de linha de comando estava " "presente::" -#: ../../library/argparse.rst:1126 +#: ../../library/argparse.rst:947 +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:954 +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:958 msgid "" "Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if " "the command-line argument was not present::" @@ -1446,11 +2058,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:961 +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:972 msgid "type" -msgstr "type" +msgstr "tipo" -#: ../../library/argparse.rst:1142 +#: ../../library/argparse.rst:974 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 +2093,7 @@ msgstr "" "que qualquer verificação de tipo e conversões de tipo necessárias sejam " "realizadas." -#: ../../library/argparse.rst:1148 +#: ../../library/argparse.rst:980 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 +2101,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:983 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:989 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:991 +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:1004 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:1006 +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:1016 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 +2178,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:1020 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 +2191,7 @@ msgstr "" "recursos mais interessante deve ser feita posteriormente, após a análise dos " "argumentos." -#: ../../library/argparse.rst:1193 +#: ../../library/argparse.rst:1025 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 +2203,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:1030 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:1037 msgid "" "For type checkers that simply check against a fixed set of values, consider " "using the choices_ keyword instead." @@ -1552,11 +2227,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:1044 msgid "choices" msgstr "choices" -#: ../../library/argparse.rst:1213 +#: ../../library/argparse.rst:1046 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 +2246,27 @@ 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:1052 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::" -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::" - -#: ../../library/argparse.rst:1240 +">>> 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:1061 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 +2275,7 @@ msgstr "" "objetos :class:`list`, objetos :class:`tuple` e sequências personalizadas " "são todos suportados." -#: ../../library/argparse.rst:1243 +#: ../../library/argparse.rst:1064 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 +2283,28 @@ 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:1067 +msgid "" +"Note that *choices* are checked after any type_ conversions have been " +"performed, so objects in *choices* should match the type_ specified. This " +"can make *choices* appear unfamiliar in usage, help, or error messages." +msgstr "" +"Observe que *choices* são verificadas após a realização de quaisquer " +"conversões de type_, portanto, os objetos em *choices* devem corresponder ao " +"type_ especificado. Isso pode fazer com que *choices* pareçam estranhos no " +"uso, na ajuda ou em mensagens de erro." + +#: ../../library/argparse.rst:1072 +msgid "" +"To keep *choices* user-friendly, consider a custom type wrapper that " +"converts and formats values, or omit type_ and handle conversion in your " +"application code." +msgstr "" +"Para manter *choices* fácel de usar, considere um invólucro de tipo " +"personalizado que converta e formate valores, ou omita type_ e lide com a " +"conversão no código da sua aplicação." + +#: ../../library/argparse.rst:1076 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 +2316,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:1085 msgid "required" msgstr "required" -#: ../../library/argparse.rst:1257 +#: ../../library/argparse.rst:1087 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:1092 +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:1100 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 +2361,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:1106 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 +2370,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:1113 msgid "help" msgstr "help" -#: ../../library/argparse.rst:1285 +#: ../../library/argparse.rst:1115 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:1120 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 +2400,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:1125 +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:1137 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 +2435,126 @@ msgstr "" "que um literal ``%`` apareça na string de ajuda, você deve escapá-lo como ``%" "%``." -#: ../../library/argparse.rst:1325 +#: ../../library/argparse.rst:1140 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:1143 +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:1155 msgid "metavar" msgstr "metavar" -#: ../../library/argparse.rst:1342 +#: ../../library/argparse.rst:1157 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:1166 +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:1181 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:1183 +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:1198 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 +2564,7 @@ msgstr "" "no objeto :meth:`~ArgumentParser.parse_args` ainda é determinado pelo valor " "dest_." -#: ../../library/argparse.rst:1387 +#: ../../library/argparse.rst:1202 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 +2574,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:1206 +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:1221 msgid "dest" msgstr "dest" -#: ../../library/argparse.rst:1408 +#: ../../library/argparse.rst:1223 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 +2618,19 @@ msgstr "" "é normalmente fornecido como o primeiro argumento para :meth:" "`~ArgumentParser.add_argument`::" -#: ../../library/argparse.rst:1420 +#: ../../library/argparse.rst:1230 +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:1235 msgid "" "For optional argument actions, the value of ``dest`` is normally inferred " "from the option strings. :class:`ArgumentParser` generates the value of " @@ -1782,16 +2650,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:1244 +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:1252 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:1254 +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:1263 msgid "deprecated" msgstr "deprecated" -#: ../../library/argparse.rst:1450 +#: ../../library/argparse.rst:1265 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 +2697,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 +2705,354 @@ 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::" - -#: ../../library/argparse.rst:1473 +"um aviso será enviado para :data:`sys.stderr` (saída de erro) quando o " +"argumento for usado::" + +#: ../../library/argparse.rst:1275 +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:1288 msgid "Action classes" msgstr "Classes de ação" -#: ../../library/argparse.rst:1475 +#: ../../library/argparse.rst:1290 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:1299 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:1305 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:1313 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:1316 +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:1318 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:1322 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:1326 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:1330 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:1335 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 -msgid "The parse_args() method" +#: ../../library/argparse.rst:1341 +msgid "" +"A subclass of :class:`Action` for handling boolean flags with positive and " +"negative options. Adding a single argument such as ``--foo`` automatically " +"creates both ``--foo`` and ``--no-foo`` options, storing ``True`` and " +"``False`` respectively::" +msgstr "" +"Uma subclasse de :class:`Action` para manipular sinalizadores booleanos com " +"opções positivas e negativas. Adicionar um único argumento, como ``--foo``, " +"cria automaticamente as opções ``--foo`` e ``--no-foo``, armazenando " +"``True`` e ``False`` respectivamente::" + +#: ../../library/argparse.rst:1346 +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:1356 +msgid "The parse_args() method" +msgstr "O método parse_args()" -#: ../../library/argparse.rst:1524 +#: ../../library/argparse.rst:1360 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:1363 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:1367 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:1370 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:1375 msgid "Option value syntax" -msgstr "" +msgstr "Sintaxe de valores da opção" -#: ../../library/argparse.rst:1541 +#: ../../library/argparse.rst:1377 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:1553 +#: ../../library/argparse.rst:1381 +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:1389 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:1393 +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:1396 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:1399 +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:1402 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:1578 +#: ../../library/argparse.rst:1405 +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:1414 msgid "Invalid arguments" msgstr "Argumentos inválidos" -#: ../../library/argparse.rst:1580 +#: ../../library/argparse.rst:1416 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:1421 +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:1442 msgid "Arguments containing ``-``" msgstr "Argumentos contendo ``-``" -#: ../../library/argparse.rst:1608 +#: ../../library/argparse.rst:1444 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 +3063,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:1452 +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:1482 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:1487 +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:1490 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:1496 msgid "Argument abbreviations (prefix matching)" -msgstr "" +msgstr "Abreviações de argumento (correspondência de prefixo)" -#: ../../library/argparse.rst:1662 +#: ../../library/argparse.rst:1498 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:1502 +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:1513 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:1519 msgid "Beyond ``sys.argv``" msgstr "Além do ``sys.argv``" -#: ../../library/argparse.rst:1685 -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::" -msgstr "" +#: ../../library/argparse.rst:1521 +msgid "" +"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:1526 +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:1705 +#: ../../library/argparse.rst:1541 msgid "The Namespace object" msgstr "O objeto Namespace" -#: ../../library/argparse.rst:1709 +#: ../../library/argparse.rst:1545 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:1548 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:1552 +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:1722 +#: ../../library/argparse.rst:1558 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 "" - -#: ../../library/argparse.rst:1738 +"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:1562 +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:1574 msgid "Other utilities" -msgstr "" +msgstr "Outros utilitários" -#: ../../library/argparse.rst:1741 +#: ../../library/argparse.rst:1577 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:1584 +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:1596 msgid "Description of parameters:" msgstr "Descrição de parâmetros:" -#: ../../library/argparse.rst:1762 +#: ../../library/argparse.rst:1598 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:1602 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:1605 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:1609 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:1612 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:1615 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:1618 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:1621 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:1623 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:1626 msgid "Some example usage::" msgstr "Alguns exemplos de uso::" -#: ../../library/argparse.rst:1811 +#: ../../library/argparse.rst:1628 +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:1647 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 +3490,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:1654 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 +3505,233 @@ msgid "" "subparser command, however, can be given by supplying the ``help=`` argument " "to :meth:`~_SubParsersAction.add_parser` as above.)" msgstr "" +"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:1854 +#: ../../library/argparse.rst:1662 +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:1690 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:1694 +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:1711 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:1887 +#: ../../library/argparse.rst:1716 +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:1723 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:1737 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 "" - -#: ../../library/argparse.rst:1938 +"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:1742 +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:1774 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 +3740,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:1781 +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:1790 +msgid "New *required* keyword-only parameter." +msgstr "Novo parâmetro somente-nomeado *required*." -#: ../../library/argparse.rst:1959 +#: ../../library/argparse.rst:1795 msgid "FileType objects" msgstr "Objetos FileType" -#: ../../library/argparse.rst:1963 +#: ../../library/argparse.rst:1799 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 +3784,324 @@ msgid "" "with the requested modes, buffer sizes, encodings and error handling (see " "the :func:`open` function for more details)::" msgstr "" +"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:1805 +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:1975 +#: ../../library/argparse.rst:1811 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:1815 +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:1989 +#: ../../library/argparse.rst:1820 +msgid "Added the *encodings* and *errors* parameters." +msgstr "Adicionados os parâmetros *encodings* e *errors*." + +#: ../../library/argparse.rst:1825 msgid "Argument groups" -msgstr "Grupos de Argumentos" +msgstr "Grupos de argumentos" -#: ../../library/argparse.rst:1993 +#: ../../library/argparse.rst:1830 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:1836 +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:1847 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:1855 +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:1873 +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:1878 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:1881 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:1889 msgid "Mutual exclusion" -msgstr "Exclusão Mútua" +msgstr "Exclusão mútua" -#: ../../library/argparse.rst:2051 +#: ../../library/argparse.rst:1893 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:1897 +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:1909 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:1913 +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:1921 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:1927 +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:1944 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:1952 msgid "Parser defaults" -msgstr "" +msgstr "Padrões do analisador sintático" -#: ../../library/argparse.rst:2114 +#: ../../library/argparse.rst:1956 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,303 +4109,455 @@ 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:1962 +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:2126 +#: ../../library/argparse.rst:1968 msgid "" -"Note that parser-level defaults always override argument-level defaults::" +"Note that defaults can be set at both the parser level using :meth:" +"`set_defaults` and at the argument level using :meth:`add_argument`. If both " +"are called for the same argument, the last default set for an argument is " +"used::" msgstr "" +"Observe que os valores padrão podem ser definidos tanto no nível do " +"analisador sintático usando :meth:`set_defaults` quanto no nível do " +"argumento usando :meth:`add_argument`. Se ambos forem chamados para o mesmo " +"argumento, o último valor padrão definido para o argumento será usado." -#: ../../library/argparse.rst:2134 +#: ../../library/argparse.rst:1972 +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:1978 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:1984 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:1988 +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:2151 +#: ../../library/argparse.rst:1995 msgid "Printing help" msgstr "Imprimindo a ajuda" -#: ../../library/argparse.rst:2153 +#: ../../library/argparse.rst:1997 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:2003 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:2009 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:2013 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:2018 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:2023 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:2028 msgid "Partial parsing" msgstr "Análise parcial" -#: ../../library/argparse.rst:2188 +#: ../../library/argparse.rst:2032 +msgid "" +"Sometimes a script only needs to handle a specific set of command-line " +"arguments, leaving any unrecognized arguments for another script or program. " +"In these cases, the :meth:`~ArgumentParser.parse_known_args` method can be " +"useful." +msgstr "" +"Às vezes, um script precisa manipular apenas um conjunto específico de " +"argumentos de linha de comando, deixando quaisquer argumentos não " +"reconhecidos para outro script ou programa. Nesses casos, o método :meth:" +"`~ArgumentParser.parse_known_args` pode ser útil." + +#: ../../library/argparse.rst:2037 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 " -"cases, the :meth:`~ArgumentParser.parse_known_args` method can be useful. " -"It works much like :meth:`~ArgumentParser.parse_args` except that it does " -"not produce an error when extra arguments are present. Instead, it returns " -"a two item tuple containing the populated namespace and the list of " -"remaining argument strings." +"This method works similarly to :meth:`~ArgumentParser.parse_args`, but it " +"does not raise an error for extra, unrecognized arguments. Instead, it " +"parses the known arguments and returns a two item tuple that contains the " +"populated namespace and the list of any unrecognized arguments." msgstr "" +"Este método funciona de forma semelhante a :meth:`~ArgumentParser." +"parse_args`, mas não levanta erro para argumentos extras não reconhecidos. " +"Em vez disso, ele analisa os argumentos conhecidos e retorna uma tupla de " +"dois itens que contém o espaço de nomes preenchido e a lista de quaisquer " +"argumentos não reconhecidos." -#: ../../library/argparse.rst:2204 +#: ../../library/argparse.rst:2044 +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:2051 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:2058 msgid "Customizing file parsing" -msgstr "" +msgstr "Personalizando a análise de arquivos" -#: ../../library/argparse.rst:2215 +#: ../../library/argparse.rst:2062 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:2067 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:2071 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:2233 +#: ../../library/argparse.rst:2074 +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:2080 msgid "Exiting methods" -msgstr "Métodos existentes" +msgstr "Métodos de saída" -#: ../../library/argparse.rst:2237 +#: ../../library/argparse.rst:2084 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:2088 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:2096 +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:2101 +msgid "Intermixed parsing" +msgstr "Análise misturada" -#: ../../library/argparse.rst:2259 +#: ../../library/argparse.rst:2106 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:2111 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:2116 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:2122 +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:2131 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 "" +":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: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 +#: ../../library/argparse.rst:2140 +msgid "Registering custom types or actions" +msgstr "Registrando ações e tipos personalizados" + +#: ../../library/argparse.rst:2144 +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:2149 +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:2154 +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:2156 +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:2168 msgid "Exceptions" msgstr "Exceções" -#: ../../library/argparse.rst:2349 +#: ../../library/argparse.rst:2172 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:2174 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:2179 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:2183 +msgid "Guides and Tutorials" +msgstr "Guias e tutoriais" -#: ../../library/argparse.rst:982 +#: ../../library/argparse.rst:809 msgid "? (question mark)" msgstr "? (interrogação)" -#: ../../library/argparse.rst:982 ../../library/argparse.rst:1016 -#: ../../library/argparse.rst:1030 +#: ../../library/argparse.rst:809 ../../library/argparse.rst:843 +#: ../../library/argparse.rst:857 msgid "in argparse module" -msgstr "" +msgstr "no módulo argparse" -#: ../../library/argparse.rst:1016 +#: ../../library/argparse.rst:843 msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../library/argparse.rst:1030 +#: ../../library/argparse.rst:857 msgid "+ (plus)" msgstr "+ (mais)" diff --git a/library/array.po b/library/array.po index 445069b18..ce4d2ad29 100644 --- a/library/array.po +++ b/library/array.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +127,10 @@ msgstr "Py_UCS4" msgid "4" msgstr "4" +#: ../../library/array.rst:27 +msgid "\\(2)" +msgstr "\\(2)" + #: ../../library/array.rst:29 msgid "``'h'``" msgstr "``'h'``" @@ -206,7 +206,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,39 +230,49 @@ 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 +#: ../../library/array.rst:67 msgid "" "The actual representation of values is determined by the machine " "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 +#: ../../library/array.rst:71 msgid "The module defines the following item:" -msgstr "" +msgstr "O módulo define o seguinte item:" -#: ../../library/array.rst:73 +#: ../../library/array.rst:76 msgid "A string with all available type codes." msgstr "String com todos os códigos de tipo disponíveis." -#: ../../library/array.rst:76 +#: ../../library/array.rst:79 msgid "The module defines the following type:" msgstr "O módulo define o seguinte tipo:" -#: ../../library/array.rst:81 +#: ../../library/array.rst:84 msgid "" "A new array whose items are restricted by *typecode*, and initialized from " "the optional *initializer* value, which must be a :class:`bytes` or :class:" "`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 +#: ../../library/array.rst:89 msgid "" "If given a :class:`bytes` or :class:`bytearray` object, the initializer is " "passed to the new array's :meth:`frombytes` method; if given a Unicode " @@ -270,8 +280,13 @@ 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 +#: ../../library/array.rst:96 msgid "" "Array objects support the ordinary sequence operations of indexing, slicing, " "concatenation, and multiplication. When using slice assignment, the " @@ -280,14 +295,14 @@ 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 similares ` é permitido." -#: ../../library/array.rst:99 +#: ../../library/array.rst:102 msgid "" "Raises an :ref:`auditing event ` ``array.__new__`` with arguments " "``typecode``, ``initializer``." @@ -295,19 +310,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``array.__new__`` com os " "argumentos ``typecode``, ``initializer``." -#: ../../library/array.rst:104 +#: ../../library/array.rst:107 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 +#: ../../library/array.rst:112 msgid "The length in bytes of one array item in the internal representation." msgstr "O tamanho em bytes de um item do vetor em representação interna." -#: ../../library/array.rst:114 +#: ../../library/array.rst:117 msgid "Append a new item with value *x* to the end of the array." msgstr "Adiciona um novo item com valor *x* ao final do vetor." -#: ../../library/array.rst:119 +#: ../../library/array.rst:122 msgid "" "Return a tuple ``(address, length)`` giving the current memory address and " "the length in elements of the buffer used to hold array's contents. The " @@ -318,8 +333,16 @@ 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 +#: ../../library/array.rst:132 msgid "" "When using array objects from code written in C or C++ (the only way to " "effectively make use of this information), it makes more sense to use the " @@ -333,7 +356,7 @@ msgstr "" "retrocompatibilidade e deve ser evitado em código novo. A interface de " "buffers está documentada em :ref:`bufferobjects`." -#: ../../library/array.rst:138 +#: ../../library/array.rst:141 msgid "" "\"Byteswap\" all items of the array. This is only supported for values " "which are 1, 2, 4, or 8 bytes in size; for other types of values, :exc:" @@ -342,15 +365,15 @@ 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." -#: ../../library/array.rst:146 +#: ../../library/array.rst:149 msgid "Return the number of occurrences of *x* in the array." msgstr "Retorna a quantidade de ocorrências de *x* no vetor." -#: ../../library/array.rst:151 +#: ../../library/array.rst:154 msgid "" "Append items from *iterable* to the end of the array. If *iterable* is " "another array, it must have *exactly* the same type code; if not, :exc:" @@ -362,18 +385,22 @@ msgstr "" "uma :exc:`TypeError`. Se *iterable* não for um vetor, ele deve ser iterável " "e seus elementos devem ser do tipo correto para ser acrescentado ao vetor." -#: ../../library/array.rst:159 +#: ../../library/array.rst:162 msgid "" "Appends items from the :term:`bytes-like object`, interpreting its content " "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 de valores de máquina (como se tivesse sido lido de " +"um arquivo usando o método :meth:`fromfile`)." -#: ../../library/array.rst:163 +#: ../../library/array.rst:166 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 +#: ../../library/array.rst:172 msgid "" "Read *n* items (as machine values) from the :term:`file object` *f* and " "append them to the end of the array. If less than *n* items are available, :" @@ -385,64 +412,73 @@ msgstr "" "*n* itens, :exc:`EOFError` é levantada, mas os itens disponíveis ainda são " "inseridos ao final do vetor." -#: ../../library/array.rst:177 +#: ../../library/array.rst:180 msgid "" "Append items from the list. This is equivalent to ``for x in list: a." "append(x)`` except that if there is a type error, the array is unchanged." msgstr "" "Adiciona itens de *list*. Isso é equivalente a ``for x in list: a." -"append(x)`` exceto que se ocorrer um errro de tipo, o vetor não é alterado." +"append(x)`` exceto que se ocorrer um erro de tipo, o vetor não é alterado." -#: ../../library/array.rst:183 +#: ../../library/array.rst:186 msgid "" "Extends this array with data from the given Unicode string. The array must " "have type code ``'u'`` or ``'w'``; otherwise a :exc:`ValueError` is raised. " "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 +#: ../../library/array.rst:194 msgid "" "Return the smallest *i* such that *i* is the index of the first occurrence " "of *x* in the array. The optional arguments *start* and *stop* can be " "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 +#: ../../library/array.rst:199 msgid "Added optional *start* and *stop* parameters." -msgstr "" +msgstr "Adicionados os parâmetros opcionais *start e *stop*." -#: ../../library/array.rst:202 +#: ../../library/array.rst:205 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 +#: ../../library/array.rst:211 msgid "" "Removes the item with the index *i* from the array and returns it. The " "optional argument defaults to ``-1``, so that by default the last item is " "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 +#: ../../library/array.rst:218 msgid "Remove the first occurrence of *x* from the array." msgstr "Remove a primeira ocorrência de *x* do vetor." -#: ../../library/array.rst:220 +#: ../../library/array.rst:223 msgid "Remove all elements from the array." -msgstr "" +msgstr "Remove todos os elementos do vetor." -#: ../../library/array.rst:227 +#: ../../library/array.rst:230 msgid "Reverse the order of the items in the array." msgstr "Inverte a ordem dos itens no vetor." -#: ../../library/array.rst:232 +#: ../../library/array.rst:235 msgid "" "Convert the array to an array of machine values and return the bytes " "representation (the same sequence of bytes that would be written to a file " @@ -452,28 +488,32 @@ msgstr "" "representação em bytes (a mesma sequência de bytes que seria escrita pelo " "método :meth:`tofile`.)" -#: ../../library/array.rst:236 +#: ../../library/array.rst:239 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 +#: ../../library/array.rst:245 msgid "Write all items (as machine values) to the :term:`file object` *f*." msgstr "" "Escreve todos os itens (como valores de máquinas) para o :term:`objeto " "arquivo ` *f*." -#: ../../library/array.rst:247 +#: ../../library/array.rst:250 msgid "Convert the array to an ordinary list with the same items." msgstr "Devolve os itens do vetor como uma lista comum." -#: ../../library/array.rst:252 +#: ../../library/array.rst:255 msgid "" "Convert the array to a Unicode string. The array must have a type ``'u'`` " "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 +#: ../../library/array.rst:260 msgid "" "The string representation of array objects has the form ``array(typecode, " "initializer)``. The *initializer* is omitted if the array is empty, " @@ -485,23 +525,43 @@ msgid "" "must also be defined if it contains corresponding floating-point values. " "Examples::" msgstr "" +"A representação em string de objetos vetor tem o formato ``array(typecode, " +"initializer)``. O *initializer* é omitido se o vetor estiver vazio; caso " +"contrário, é uma string Unicode se o *typecode* for ``'u'`` ou ``'w'``; caso " +"contrário, é uma lista de números. A representação em string pode ser " +"convertida novamente para um array com o mesmo tipo e valor usando :func:" +"`eval`, desde que a classe :class:`~array.array` tenha sido importada usando " +"``from array import array``. As variáveis ``inf`` e ``nan`` também devem ser " +"definidas se contiverem valores de ponto flutuante correspondentes. Exemplos:" -#: ../../library/array.rst:277 +#: ../../library/array.rst:272 +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:280 msgid "Module :mod:`struct`" msgstr "Módulo :mod:`struct`" -#: ../../library/array.rst:278 +#: ../../library/array.rst:281 msgid "Packing and unpacking of heterogeneous binary data." msgstr "Empacotamento e desempacotamento de dados binários heterogêneos." -#: ../../library/array.rst:280 +#: ../../library/array.rst:283 msgid "`NumPy `_" -msgstr "" +msgstr "`NumPy `_" -#: ../../library/array.rst:281 +#: ../../library/array.rst:284 msgid "The NumPy package defines another array type." -msgstr "" +msgstr "O pacote NumPy define outro tipo de vetor." #: ../../library/array.rst:7 msgid "arrays" -msgstr "" +msgstr "vetores" diff --git a/library/ast.po b/library/ast.po index 803f84283..9a088bf70 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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" @@ -372,14 +820,15 @@ msgstr "Literais" msgid "" "A constant value. The ``value`` attribute of the ``Constant`` literal " "contains the Python object it represents. The values represented can be " -"simple types such as a number, string or ``None``, but also immutable " -"container types (tuples and frozensets) if all of their elements are " -"constant." +"instances of :class:`str`, :class:`bytes`, :class:`int`, :class:`float`, :" +"class:`complex`, and :class:`bool`, and the constants :data:`None` and :data:" +"`Ellipsis`." msgstr "" "Um valor constante. O atributo ``value`` do literal ``Constant`` contém o " -"objeto Python que ele representa. Os valores representados podem ser tipos " -"simples como um número, string ou ``None``, mas também tipos de contêineres " -"imutáveis (tuplas e frozensets) se todos os seus elementos forem constantes." +"objeto Python que ele representa. Os valores representados podem ser " +"instâncias de :class:`str`, :class:`bytes`, :class:`int`, :class:`float`, :" +"class:`complex` e :class:`bool`, e as constantes :data:`None` e :data:" +"`Ellipsis`." #: ../../library/ast.rst:279 msgid "" @@ -437,6 +886,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 +938,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 +1018,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 +1062,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 +1116,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 +1164,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 +1198,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 +1220,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 +1255,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 +1287,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 +1325,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 +1343,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 +1396,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 +1424,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 +1452,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 +1482,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 +1520,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 +1558,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 +1662,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 +1802,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 +1871,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 +1982,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 +2011,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 +2035,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 +2059,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 +2107,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 +2140,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 +2172,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 +2204,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 +2256,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 +2324,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 +2370,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 +2472,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 +2558,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 +2611,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 +2677,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 +2765,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 +2844,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 +2891,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 +2938,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 +2994,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 +3087,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 +3188,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 +3294,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 +3364,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 +3488,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 +3680,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 +3702,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 +3744,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 +3752,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 +3770,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 +3878,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 +3984,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 +4048,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 +4056,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 +4098,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 +4112,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 +4124,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 +4136,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 +4151,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 +4159,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 +4169,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 +4191,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 +4213,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 +4221,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 +4230,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 +4243,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 +4253,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 +4263,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 +4271,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 +4283,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 +4294,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 +4315,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 +4323,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 +4331,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 +4357,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 +4373,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 +4381,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 +4397,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 +4407,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 +4417,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 +4425,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 +4433,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 +4444,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 +4454,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 +4462,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 +4472,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 +4485,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 +4499,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 +4511,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 +4519,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 +4533,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 +4541,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 +4571,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 +4581,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 +4593,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 +4627,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,27 +4643,79 @@ 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." +"If *show_empty* is false (the default), optional empty lists will be omitted " +"from the output. Optional ``None`` values are always omitted." msgstr "" -"Se *show_empty* for ``False`` (o padrão), listas vazias e campos que forem " -"``None`` serão omitidos da saída." +"Se *show_empty* for falso (o padrão), listas vazias opcionais serão omitidas " +"da saída. Valores opcionais ``None`` são sempre omitidos." -#: ../../library/ast.rst:2410 +#: ../../library/ast.rst:2447 msgid "Added the *indent* option." msgstr "Adicionada a opção *indent*." -#: ../../library/ast.rst:2413 +#: ../../library/ast.rst:2450 msgid "Added the *show_empty* option." msgstr "Adicionada a opção *show_empty*." -#: ../../library/ast.rst:2447 +#: ../../library/ast.rst:2453 +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:2484 msgid "Compiler Flags" msgstr "Sinalizadores do compilador" -#: ../../library/ast.rst:2449 +#: ../../library/ast.rst:2486 msgid "" "The following flags may be passed to :func:`compile` in order to change " "effects on the compilation of a program:" @@ -1958,7 +4723,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:2491 msgid "" "Enables support for top-level ``await``, ``async for``, ``async with`` and " "async comprehensions." @@ -1966,7 +4731,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:2498 msgid "" "Generates and returns an abstract syntax tree instead of returning a " "compiled code object." @@ -1974,7 +4739,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:2503 msgid "" "The returned AST is optimized according to the *optimize* argument in :func:" "`compile` or :func:`ast.parse`." @@ -1982,7 +4747,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:2510 msgid "" "Enables support for :pep:`484` and :pep:`526` style type comments (``# type: " "``, ``# type: ignore ``)." @@ -1990,11 +4755,11 @@ msgstr "" "Habilita suporte para comentários do tipo :pep:`484` e :pep:`526` (``# type: " "``, ``# type: ignore ``)." -#: ../../library/ast.rst:2482 +#: ../../library/ast.rst:2519 msgid "Command-Line Usage" msgstr "Uso na linha de comando" -#: ../../library/ast.rst:2486 +#: ../../library/ast.rst:2523 msgid "" "The :mod:`ast` module can be executed as a script from the command line. It " "is as simple as:" @@ -2002,15 +4767,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:2526 +msgid "python -m ast [-m ] [-a] [infile]" +msgstr "python -m ast [-m ] [-a] [infile]" + +#: ../../library/ast.rst:2530 msgid "The following options are accepted:" msgstr "As seguintes opções são aceitas:" -#: ../../library/ast.rst:2499 +#: ../../library/ast.rst:2536 msgid "Show the help message and exit." msgstr "Mostra a mensagem de ajuda e sai." -#: ../../library/ast.rst:2504 +#: ../../library/ast.rst:2541 msgid "" "Specify what kind of code must be compiled, like the *mode* argument in :" "func:`parse`." @@ -2018,19 +4787,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:2546 msgid "Don't parse type comments." msgstr "Não analisa comentários de tipo." -#: ../../library/ast.rst:2513 +#: ../../library/ast.rst:2550 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:2555 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:2557 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 +4807,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:2563 msgid "" "`Green Tree Snakes `_, an external " "documentation resource, has good details on working with Python ASTs." @@ -2047,7 +4816,7 @@ msgstr "" "de documentação externo, possui bons detalhes sobre trabalhar com ASTs do " "Python." -#: ../../library/ast.rst:2529 +#: ../../library/ast.rst:2566 msgid "" "`ASTTokens `_ " "annotates Python ASTs with the positions of tokens and text in the source " @@ -2059,7 +4828,7 @@ msgstr "" "as gerou. Isso é útil para ferramentas que fazem transformações de código-" "fonte." -#: ../../library/ast.rst:2534 +#: ../../library/ast.rst:2571 msgid "" "`leoAst.py `_ unifies the token-based and parse-tree-based views of python programs " @@ -2069,7 +4838,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:2576 msgid "" "`LibCST `_ parses code as a Concrete Syntax " "Tree that looks like an ast tree and keeps all formatting details. It's " @@ -2080,7 +4849,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:2581 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..64480ad21 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..019854c17 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..fde1bf14d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..7f3a05a02 100644 --- a/library/asyncio-eventloop.po +++ b/library/asyncio-eventloop.po @@ -1,34 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +252,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 +312,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 +328,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:1338 +#: ../../library/asyncio-eventloop.rst:1793 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 +355,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 +365,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 +375,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 +397,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 +411,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 +445,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 +453,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:307 +#: ../../library/asyncio-eventloop.rst:333 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " "details." @@ -464,7 +463,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 +471,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 +487,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 +500,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 +508,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:324 msgid "" "An instance of :class:`asyncio.TimerHandle` is returned which can be used to " "cancel the callback." @@ -511,7 +517,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 +526,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 +536,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 +546,14 @@ 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:303 +msgid "" +"For performance, callbacks scheduled with :meth:`loop.call_later` may run up " +"to one clock-resolution early (see ``time.get_clock_info('monotonic')." +"resolution``)." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:311 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 +561,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:318 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 +570,18 @@ 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:322 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:329 +msgid "" +"For performance, callbacks scheduled with :meth:`loop.call_at` may run up to " +"one clock-resolution early (see ``time.get_clock_info('monotonic')." +"resolution``)." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:337 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 +591,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:344 msgid "" "Return the current time, as a :class:`float` value, according to the event " "loop's internal monotonic clock." @@ -579,7 +599,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:348 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 +607,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:354 msgid "The :func:`asyncio.sleep` function." msgstr "A função :func:`asyncio.sleep`." -#: ../../library/asyncio-eventloop.rst:341 +#: ../../library/asyncio-eventloop.rst:358 msgid "Creating Futures and Tasks" msgstr "Criando Futures e Tasks" -#: ../../library/asyncio-eventloop.rst:345 +#: ../../library/asyncio-eventloop.rst:362 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." +msgstr "Cria um objeto :class:`asyncio.Future` anexado ao laço de eventos." -#: ../../library/asyncio-eventloop.rst:347 +#: ../../library/asyncio-eventloop.rst:364 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 +629,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:372 msgid "" "Schedule the execution of :ref:`coroutine ` *coro*. Return a :" "class:`Task` object." msgstr "" -#: ../../library/asyncio-eventloop.rst:358 +#: ../../library/asyncio-eventloop.rst:375 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 +645,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:379 +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:384 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 +661,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:387 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:391 msgid "Added the *name* parameter." msgstr "Adicionado o parâmetro *name*." -#: ../../library/asyncio-eventloop.rst:372 +#: ../../library/asyncio-eventloop.rst:394 msgid "Added the *context* parameter." msgstr "Adicionado o parâmetro *context*." -#: ../../library/asyncio-eventloop.rst:377 +#: ../../library/asyncio-eventloop.rst:397 +msgid "" +"Added ``kwargs`` which passes on arbitrary extra parameters, including " +"``name`` and ``context``." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:400 +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:406 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:409 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:415 +msgid "Required that all *kwargs* are passed on to :class:`asyncio.Task`." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:418 +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:424 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:428 msgid "Opening network connections" msgstr "Abrindo conexões de rede" -#: ../../library/asyncio-eventloop.rst:403 +#: ../../library/asyncio-eventloop.rst:440 msgid "" "Open a streaming transport connection to a given address specified by *host* " "and *port*." @@ -679,20 +730,23 @@ 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:443 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 "" +"A família de sockets pode ser :py:const:`~socket.AF_INET` ou :py:const:" +"`~socket.AF_INET6` dependendo do *host* (ou do argumento *family*, se " +"fornecido)." -#: ../../library/asyncio-eventloop.rst:410 +#: ../../library/asyncio-eventloop.rst:447 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:449 +#: ../../library/asyncio-eventloop.rst:1248 +#: ../../library/asyncio-eventloop.rst:1265 msgid "" "*protocol_factory* must be a callable returning an :ref:`asyncio protocol " "` implementation." @@ -700,7 +754,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:452 msgid "" "This method will try to establish the connection in the background. When " "successful, it returns a ``(transport, protocol)`` pair." @@ -708,11 +762,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:455 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:457 msgid "" "The connection is established and a :ref:`transport ` is " "created for it." @@ -720,7 +774,7 @@ msgstr "" "A conexão é estabelecida e um :ref:`transporte ` é criado " "para ela." -#: ../../library/asyncio-eventloop.rst:423 +#: ../../library/asyncio-eventloop.rst:460 msgid "" "*protocol_factory* is called without arguments and is expected to return a :" "ref:`protocol ` instance." @@ -728,7 +782,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:463 msgid "" "The protocol instance is coupled with the transport by calling its :meth:" "`~BaseProtocol.connection_made` method." @@ -736,22 +790,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:466 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:468 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:471 +#: ../../library/asyncio-eventloop.rst:604 msgid "Other arguments:" msgstr "Outros argumentos:" -#: ../../library/asyncio-eventloop.rst:436 +#: ../../library/asyncio-eventloop.rst:473 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 +819,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:479 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:481 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 +841,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:489 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 +853,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:494 msgid "" "*happy_eyeballs_delay*, if given, enables Happy Eyeballs for this " "connection. It should be a floating-point number representing the amount of " @@ -813,9 +867,9 @@ msgstr "" "segundos para aguardar uma tentativa de conexão encerrar, antes de começar a " "próxima tentativa em paralelo. Este é o \"Atraso na tentativa de conexão\" " "conforme definido na :rfc:`8305`. Um valor padrão sensível recomendado pela " -"RFC é ``0.25`` (250 millisegundos)." +"RFC é ``0.25`` (250 millissegundos)." -#: ../../library/asyncio-eventloop.rst:465 +#: ../../library/asyncio-eventloop.rst:502 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 +888,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:511 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 +901,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:519 +#: ../../library/asyncio-eventloop.rst:641 +#: ../../library/asyncio-eventloop.rst:889 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:523 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 +921,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:527 +#: ../../library/asyncio-eventloop.rst:985 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 +932,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:531 +#: ../../library/asyncio-eventloop.rst:796 +#: ../../library/asyncio-eventloop.rst:900 +#: ../../library/asyncio-eventloop.rst:989 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:535 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 +952,27 @@ msgid "" "(even if there is only one)." msgstr "" -#: ../../library/asyncio-eventloop.rst:508 -#: ../../library/asyncio-eventloop.rst:762 +#: ../../library/asyncio-eventloop.rst:545 +#: ../../library/asyncio-eventloop.rst:808 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:549 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:554 +#: ../../library/asyncio-eventloop.rst:910 msgid "Added the *ssl_handshake_timeout* parameter." msgstr "Adicionado o parâmetro *ssl_handshake_timeout*." -#: ../../library/asyncio-eventloop.rst:521 +#: ../../library/asyncio-eventloop.rst:558 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:560 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 +983,24 @@ msgid "" "visible delay and provides an algorithm." msgstr "" -#: ../../library/asyncio-eventloop.rst:532 +#: ../../library/asyncio-eventloop.rst:569 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:573 +#: ../../library/asyncio-eventloop.rst:705 +#: ../../library/asyncio-eventloop.rst:822 +#: ../../library/asyncio-eventloop.rst:862 +#: ../../library/asyncio-eventloop.rst:914 +#: ../../library/asyncio-eventloop.rst:997 msgid "Added the *ssl_shutdown_timeout* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:538 +#: ../../library/asyncio-eventloop.rst:575 msgid "*all_errors* was added." msgstr "" -#: ../../library/asyncio-eventloop.rst:543 +#: ../../library/asyncio-eventloop.rst:580 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 +1010,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:591 msgid "Create a datagram connection." msgstr "Cria uma conexão de datagrama." -#: ../../library/asyncio-eventloop.rst:555 +#: ../../library/asyncio-eventloop.rst:593 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:597 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:599 +#: ../../library/asyncio-eventloop.rst:732 +#: ../../library/asyncio-eventloop.rst:881 msgid "" "*protocol_factory* must be a callable returning a :ref:`protocol ` implementation." @@ -981,12 +1035,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:602 +#: ../../library/asyncio-eventloop.rst:687 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:606 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 +1050,13 @@ 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:612 +msgid "" +"On Windows, when using the proactor event loop with ``local_addr=None``, an :" +"exc:`OSError` with :attr:`!errno.WSAEINVAL` will be raised when running it." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:616 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 +1066,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:620 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 +1078,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:625 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 +1087,7 @@ msgid "" "is not defined then this capability is unsupported." msgstr "" -#: ../../library/asyncio-eventloop.rst:587 +#: ../../library/asyncio-eventloop.rst:631 msgid "" "*allow_broadcast* tells the kernel to allow this endpoint to send messages " "to the broadcast address." @@ -1035,7 +1095,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:634 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 +1107,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:645 msgid "" "See :ref:`UDP echo client protocol ` and :" "ref:`UDP echo server protocol ` examples." @@ -1056,24 +1116,24 @@ msgstr "" "ref:`protocolo UDP eco servidor ` para " "exemplos." -#: ../../library/asyncio-eventloop.rst:604 +#: ../../library/asyncio-eventloop.rst:648 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:652 msgid "Added support for Windows." msgstr "Adicionado suporte para Windows." -#: ../../library/asyncio-eventloop.rst:611 +#: ../../library/asyncio-eventloop.rst:655 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:661 msgid "" "When multiple processes with differing UIDs assign sockets to an identical " "UDP socket address with ``SO_REUSEADDR``, incoming packets can become " @@ -1083,7 +1143,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:665 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:697 +#: ../../library/asyncio-eventloop.rst:853 +#: ../../library/asyncio-eventloop.rst:1318 +#: ../../library/asyncio-eventloop.rst:1864 +#: ../../library/asyncio-eventloop.rst:1871 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/asyncio-eventloop.rst:654 +#: ../../library/asyncio-eventloop.rst:699 msgid "" "Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be " "a :term:`path-like object`." @@ -1139,25 +1201,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:709 msgid "Creating network servers" msgstr "Criando servidores de rede" -#: ../../library/asyncio-eventloop.rst:679 +#: ../../library/asyncio-eventloop.rst:725 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:728 msgid "Returns a :class:`Server` object." msgstr "Retorna um objeto :class:`Server`." -#: ../../library/asyncio-eventloop.rst:684 +#: ../../library/asyncio-eventloop.rst:730 msgid "Arguments:" msgstr "Argumentos:" -#: ../../library/asyncio-eventloop.rst:689 +#: ../../library/asyncio-eventloop.rst:735 msgid "" "The *host* parameter can be set to several types which determine where the " "server would be listening:" @@ -1165,7 +1227,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:738 msgid "" "If *host* is a string, the TCP server is bound to a single network interface " "specified by *host*." @@ -1173,7 +1235,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:741 msgid "" "If *host* is a sequence of strings, the TCP server is bound to all network " "interfaces specified by the sequence." @@ -1181,7 +1243,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:744 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 +1253,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:748 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 +1266,18 @@ msgstr "" "interfaces de rede, uma porta aleatória diferente será selecionada para cada " "interface)." -#: ../../library/asyncio-eventloop.rst:707 +#: ../../library/asyncio-eventloop.rst:753 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:758 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:760 msgid "" "*sock* can optionally be specified in order to use a preexisting socket " "object. If specified, *host* and *port* must not be specified." @@ -1223,21 +1285,21 @@ 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:765 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:769 msgid "" "*backlog* is the maximum number of queued connections passed to :meth:" "`~socket.socket.listen` (defaults to 100)." msgstr "" -"*backlog* é o número máximo de conexões enfileiradas pasadas para :meth:" +"*backlog* é o número máximo de conexões enfileiradas passadas para :meth:" "`~socket.socket.listen` (padrão é 100)." -#: ../../library/asyncio-eventloop.rst:726 +#: ../../library/asyncio-eventloop.rst:772 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` instance to enable TLS over " "the accepted connections." @@ -1245,17 +1307,17 @@ 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:775 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 " "will automatically be set to ``True`` on Unix." msgstr "" "*reuse_address* diz ao kernel para reusar um soquete local em estado " -"``TIME_WAIT``, serm aguardar pela expiração natural do seu tempo limite. Se " +"``TIME_WAIT``, sem 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:780 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 +1328,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:785 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:790 msgid "Added the *keep_alive* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:746 +#: ../../library/asyncio-eventloop.rst:792 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 +1348,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:800 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 +1360,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:812 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:816 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:826 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 +1381,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:838 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:841 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 +1397,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:846 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:850 msgid "" "See the documentation of the :meth:`loop.create_server` method for " "information about arguments to this method." @@ -1350,23 +1412,23 @@ 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:857 msgid "" "Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path* " "parameter can now be a :class:`~pathlib.Path` object." msgstr "" -"Adicionados os parâmetros *ssl_handshake_timeout* estart_serving*. O " +"Adicionados os parâmetros *ssl_handshake_timeout* e *start_serving*. O " "parâmetros *path* agora pode ser um objeto da classe :class:`~pathlib.Path`." -#: ../../library/asyncio-eventloop.rst:819 +#: ../../library/asyncio-eventloop.rst:866 msgid "Added the *cleanup_socket* parameter." msgstr "" -#: ../../library/asyncio-eventloop.rst:826 +#: ../../library/asyncio-eventloop.rst:874 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:876 msgid "" "This method can be used by servers that accept connections outside of " "asyncio but that use asyncio to handle them." @@ -1374,12 +1436,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:879 +#: ../../library/asyncio-eventloop.rst:971 msgid "Parameters:" msgstr "Parâmetros:" -#: ../../library/asyncio-eventloop.rst:836 +#: ../../library/asyncio-eventloop.rst:884 msgid "" "*sock* is a preexisting socket object returned from :meth:`socket.accept " "`." @@ -1387,7 +1449,7 @@ msgstr "" "*sock* é um objeto soquete pré-existente retornado a partir de :meth:`socket." "accept `." -#: ../../library/asyncio-eventloop.rst:845 +#: ../../library/asyncio-eventloop.rst:893 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the " "accepted connections." @@ -1395,7 +1457,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:896 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 +1467,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:904 msgid "Returns a ``(transport, protocol)`` pair." msgstr "Retorna um par ``(transport, protocol)``." -#: ../../library/asyncio-eventloop.rst:870 +#: ../../library/asyncio-eventloop.rst:918 msgid "Transferring files" msgstr "Transferindo arquivos" -#: ../../library/asyncio-eventloop.rst:875 +#: ../../library/asyncio-eventloop.rst:924 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:927 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:929 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:931 +#: ../../library/asyncio-eventloop.rst:1192 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 +1506,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:938 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 +1516,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:942 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support the " "*sendfile* syscall and *fallback* is ``False``." @@ -1462,22 +1524,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:949 msgid "TLS Upgrade" msgstr "Atualizando TLS" -#: ../../library/asyncio-eventloop.rst:907 +#: ../../library/asyncio-eventloop.rst:957 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:959 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:963 msgid "" "Return the created two-interface instance. After *await*, the *protocol* " "must stop using the original *transport* and communicate with the returned " @@ -1485,13 +1547,13 @@ msgid "" "exchanges extra TLS session packets with *transport*." msgstr "" -#: ../../library/asyncio-eventloop.rst:918 +#: ../../library/asyncio-eventloop.rst:968 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:973 msgid "" "*transport* and *protocol* instances that methods like :meth:`~loop." "create_server` and :meth:`~loop.create_connection` return." @@ -1499,11 +1561,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:977 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:979 msgid "" "*server_side* pass ``True`` when a server-side connection is being upgraded " "(like the one created by :meth:`~loop.create_server`)." @@ -1512,7 +1574,7 @@ msgstr "" "estiver sendo atualizada (como a que é criada por :meth:`~loop." "create_server`)." -#: ../../library/asyncio-eventloop.rst:932 +#: ../../library/asyncio-eventloop.rst:982 msgid "" "*server_hostname*: sets or overrides the host name that the target server's " "certificate will be matched against." @@ -1520,11 +1582,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:1002 msgid "Watching file descriptors" msgstr "Observando descritores de arquivo" -#: ../../library/asyncio-eventloop.rst:956 +#: ../../library/asyncio-eventloop.rst:1006 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 +1595,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:1010 +#: ../../library/asyncio-eventloop.rst:1024 +msgid "" +"Any preexisting callback registered for *fd* is cancelled and replaced by " +"*callback*." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1015 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:1020 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 +1617,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:1027 +#: ../../library/asyncio-eventloop.rst:1305 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *callback*." @@ -1557,13 +1626,13 @@ msgstr "" "Use :func:`functools.partial` :ref:`para passar argumentos nomeados ` para a *callback*." -#: ../../library/asyncio-eventloop.rst:976 +#: ../../library/asyncio-eventloop.rst:1032 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:1035 msgid "" "See also :ref:`Platform Support ` section for some " "limitations of these methods." @@ -1571,11 +1640,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:1040 msgid "Working with socket objects directly" msgstr "Trabalhando com objetos soquete diretamente" -#: ../../library/asyncio-eventloop.rst:986 +#: ../../library/asyncio-eventloop.rst:1042 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 +1658,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:1052 msgid "" "Receive up to *nbytes* from *sock*. Asynchronous version of :meth:`socket." "recv() `." @@ -1597,23 +1666,23 @@ msgstr "" "Recebe até *nbytes* do *sock*. Versão assíncrona de :meth:`socket.recv() " "`." -#: ../../library/asyncio-eventloop.rst:998 +#: ../../library/asyncio-eventloop.rst:1055 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:1057 +#: ../../library/asyncio-eventloop.rst:1072 +#: ../../library/asyncio-eventloop.rst:1084 +#: ../../library/asyncio-eventloop.rst:1097 +#: ../../library/asyncio-eventloop.rst:1113 +#: ../../library/asyncio-eventloop.rst:1129 +#: ../../library/asyncio-eventloop.rst:1140 +#: ../../library/asyncio-eventloop.rst:1167 +#: ../../library/asyncio-eventloop.rst:1206 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:1059 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 +1692,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:1067 msgid "" "Receive data from *sock* into the *buf* buffer. Modeled after the blocking :" "meth:`socket.recv_into() ` method." @@ -1631,31 +1700,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:1070 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:1079 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:1082 msgid "Return a tuple of (received data, remote address)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1031 +#: ../../library/asyncio-eventloop.rst:1091 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:1095 msgid "Return a tuple of (number of bytes received, remote address)." msgstr "" -#: ../../library/asyncio-eventloop.rst:1043 +#: ../../library/asyncio-eventloop.rst:1104 msgid "" "Send *data* to the *sock* socket. Asynchronous version of :meth:`socket." "sendall() `." @@ -1663,7 +1732,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:1107 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 +1746,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:1115 +#: ../../library/asyncio-eventloop.rst:1169 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 +1757,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:1123 msgid "" "Send a datagram from *sock* to *address*. Asynchronous version of :meth:" "`socket.sendto() `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1065 +#: ../../library/asyncio-eventloop.rst:1127 msgid "Return the number of bytes sent." msgstr "" -#: ../../library/asyncio-eventloop.rst:1073 +#: ../../library/asyncio-eventloop.rst:1136 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:1138 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:1142 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 +1787,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:1151 msgid "" ":meth:`loop.create_connection` and :func:`asyncio.open_connection() " "`." @@ -1726,7 +1795,7 @@ msgstr "" ":meth:`loop.create_connection` e :func:`asyncio.open_connection() " "`." -#: ../../library/asyncio-eventloop.rst:1094 +#: ../../library/asyncio-eventloop.rst:1158 msgid "" "Accept a connection. Modeled after the blocking :meth:`socket.accept() " "` method." @@ -1734,7 +1803,7 @@ msgstr "" "Aceita uma conexão. Modelado baseado no método bloqueante :meth:`socket." "accept() `." -#: ../../library/asyncio-eventloop.rst:1097 +#: ../../library/asyncio-eventloop.rst:1161 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 +1815,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:1176 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:1182 msgid "" "Send a file using high-performance :mod:`os.sendfile` if possible. Return " "the total number of bytes sent." @@ -1758,13 +1827,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:1185 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:1187 msgid "" "*sock* must be a non-blocking :const:`socket.SOCK_STREAM` :class:`~socket." "socket`." @@ -1772,11 +1841,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:1190 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:1199 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 +1855,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:1203 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support " "*sendfile* syscall and *fallback* is ``False``." @@ -1794,19 +1863,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:1212 msgid "DNS" msgstr "DNS" -#: ../../library/asyncio-eventloop.rst:1152 +#: ../../library/asyncio-eventloop.rst:1218 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:1223 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:1226 msgid "" "Both *getaddrinfo* and *getnameinfo* internally utilize their synchronous " "versions through the loop's default thread pool executor. When this executor " @@ -1816,7 +1885,7 @@ msgid "" "executor with a larger number of workers." msgstr "" -#: ../../library/asyncio-eventloop.rst:1166 +#: ../../library/asyncio-eventloop.rst:1233 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 +1897,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:1241 msgid "Working with pipes" msgstr "Trabalhando com encadeamentos" -#: ../../library/asyncio-eventloop.rst:1178 +#: ../../library/asyncio-eventloop.rst:1246 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:1251 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:1253 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports the :class:" "`ReadTransport` interface and *protocol* is an object instantiated by the " @@ -1850,8 +1919,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:1257 +#: ../../library/asyncio-eventloop.rst:1274 msgid "" "With :class:`SelectorEventLoop` event loop, the *pipe* is set to non-" "blocking mode." @@ -1859,15 +1928,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:1263 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:1268 msgid "*pipe* is :term:`file-like object `." msgstr "*pipe* é um :term:`objeto arquivo ou similar `." -#: ../../library/asyncio-eventloop.rst:1201 +#: ../../library/asyncio-eventloop.rst:1270 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports :class:" "`WriteTransport` interface and *protocol* is an object instantiated by the " @@ -1877,7 +1946,7 @@ msgstr "" "interface :class:`WriteTransport` e *protocol* é um objeto instanciado pelo " "*protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1210 +#: ../../library/asyncio-eventloop.rst:1279 msgid "" ":class:`SelectorEventLoop` does not support the above methods on Windows. " "Use :class:`ProactorEventLoop` instead for Windows." @@ -1885,21 +1954,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:1284 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:1289 msgid "Unix signals" msgstr "Sinais Unix" -#: ../../library/asyncio-eventloop.rst:1226 +#: ../../library/asyncio-eventloop.rst:1295 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:1297 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 +1981,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:1302 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 +1990,18 @@ msgstr "" "capturar. Levanta :exc:`RuntimeError` se existe um problema definindo o " "tratador." -#: ../../library/asyncio-eventloop.rst:1239 +#: ../../library/asyncio-eventloop.rst:1308 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:1313 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:1315 msgid "" "Return ``True`` if the signal handler was removed, or ``False`` if no " "handler was set for the given signal." @@ -1940,19 +2009,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:1322 msgid "The :mod:`signal` module." msgstr "O módulo :mod:`signal`." -#: ../../library/asyncio-eventloop.rst:1257 +#: ../../library/asyncio-eventloop.rst:1326 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:1330 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:1332 msgid "" "The *executor* argument should be an :class:`concurrent.futures.Executor` " "instance. The default executor is used if *executor* is ``None``. The " @@ -1961,7 +2030,50 @@ msgid "" "and used by :func:`run_in_executor` if needed." msgstr "" -#: ../../library/asyncio-eventloop.rst:1311 +#: ../../library/asyncio-eventloop.rst:1340 +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:1380 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 +2081,11 @@ msgid "" "importing of main module `." msgstr "" -#: ../../library/asyncio-eventloop.rst:1316 +#: ../../library/asyncio-eventloop.rst:1385 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:1387 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *func*." @@ -1981,7 +2093,7 @@ msgstr "" "Use :func:`functools.partial` :ref:`para passar argumentos nomeados ` para *func*." -#: ../../library/asyncio-eventloop.rst:1321 +#: ../../library/asyncio-eventloop.rst:1390 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 +2105,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:1399 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:1403 msgid "" "*executor* must be an instance of :class:`~concurrent.futures." "ThreadPoolExecutor`." msgstr "" -#: ../../library/asyncio-eventloop.rst:1340 +#: ../../library/asyncio-eventloop.rst:1409 msgid "Error Handling API" msgstr "Tratando erros da API" -#: ../../library/asyncio-eventloop.rst:1342 +#: ../../library/asyncio-eventloop.rst:1411 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:1415 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:1417 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 +2145,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:1425 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:1431 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:1436 msgid "" "Return the current exception handler, or ``None`` if no custom exception " "handler was set." @@ -2054,11 +2166,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:1443 msgid "Default exception handler." msgstr "Tratador de exceção padrão." -#: ../../library/asyncio-eventloop.rst:1376 +#: ../../library/asyncio-eventloop.rst:1445 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 +2180,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:1449 msgid "" "*context* parameter has the same meaning as in :meth:" "`call_exception_handler`." @@ -2076,11 +2188,11 @@ msgstr "" "parâmetro *context* tem o mesmo significado que em :meth:" "`call_exception_handler`." -#: ../../library/asyncio-eventloop.rst:1385 +#: ../../library/asyncio-eventloop.rst:1454 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:1456 msgid "" "*context* is a ``dict`` object containing the following keys (new keys may " "be introduced in future Python versions):" @@ -2088,66 +2200,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:1459 msgid "'message': Error message;" msgstr "'message': Mensagem de erro;" -#: ../../library/asyncio-eventloop.rst:1391 +#: ../../library/asyncio-eventloop.rst:1460 msgid "'exception' (optional): Exception object;" msgstr "'exception' (opcional): Objeto Exception;" -#: ../../library/asyncio-eventloop.rst:1392 +#: ../../library/asyncio-eventloop.rst:1461 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:1462 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:1463 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:1464 msgid "'protocol' (optional): :ref:`Protocol ` instance;" msgstr "" "'protocol' (opcional): instância de :ref:`Protocol `;" -#: ../../library/asyncio-eventloop.rst:1396 +#: ../../library/asyncio-eventloop.rst:1465 msgid "'transport' (optional): :ref:`Transport ` instance;" msgstr "" "'transport' (opcional): instância de :ref:`Transport `;" -#: ../../library/asyncio-eventloop.rst:1397 +#: ../../library/asyncio-eventloop.rst:1466 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:1467 +msgid "'source_traceback' (optional): Traceback of the source;" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1468 +msgid "'handle_traceback' (optional): Traceback of the handle;" +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1469 msgid "'asyncgen' (optional): Asynchronous generator that caused" msgstr "'asyncgen' (opcional): Gerador assíncrono que causou" -#: ../../library/asyncio-eventloop.rst:1399 +#: ../../library/asyncio-eventloop.rst:1470 msgid "the exception." msgstr "a exceção." -#: ../../library/asyncio-eventloop.rst:1403 +#: ../../library/asyncio-eventloop.rst:1474 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:1479 msgid "Enabling debug mode" msgstr "Habilitando o modo de debug" -#: ../../library/asyncio-eventloop.rst:1412 +#: ../../library/asyncio-eventloop.rst:1483 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:1485 msgid "" "The default value is ``True`` if the environment variable :envvar:" "`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False`` otherwise." @@ -2156,11 +2273,11 @@ msgstr "" "`PYTHONASYNCIODEBUG` estiver definida para uma string não vazia, ``False`` " "caso contrário." -#: ../../library/asyncio-eventloop.rst:1420 +#: ../../library/asyncio-eventloop.rst:1491 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:1495 msgid "" "The new :ref:`Python Development Mode ` can now also be used to " "enable the debug mode." @@ -2168,26 +2285,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:1500 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:1504 msgid "Default value is 100 milliseconds." msgstr "" -#: ../../library/asyncio-eventloop.rst:1437 +#: ../../library/asyncio-eventloop.rst:1508 msgid "The :ref:`debug mode of asyncio `." msgstr "O :ref:`modo de debug de asyncio `." -#: ../../library/asyncio-eventloop.rst:1441 +#: ../../library/asyncio-eventloop.rst:1512 msgid "Running Subprocesses" msgstr "Executando Subprocessos" -#: ../../library/asyncio-eventloop.rst:1443 +#: ../../library/asyncio-eventloop.rst:1514 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 +2315,7 @@ msgstr "" "`asyncio.create_subprocess_shell` e :func:`asyncio.create_subprocess_exec` " "ao invés." -#: ../../library/asyncio-eventloop.rst:1450 +#: ../../library/asyncio-eventloop.rst:1521 msgid "" "On Windows, the default event loop :class:`ProactorEventLoop` supports " "subprocesses, whereas :class:`SelectorEventLoop` does not. See :ref:" @@ -2209,22 +2326,22 @@ msgstr "" "ref:`Suporte para subprocessos no Windows ` para " "detalhes." -#: ../../library/asyncio-eventloop.rst:1461 +#: ../../library/asyncio-eventloop.rst:1533 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:1536 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:1538 msgid ":class:`str`;" msgstr ":class:`str`;" -#: ../../library/asyncio-eventloop.rst:1467 +#: ../../library/asyncio-eventloop.rst:1539 msgid "" "or :class:`bytes`, encoded to the :ref:`filesystem encoding `." @@ -2232,7 +2349,7 @@ msgstr "" "ou :class:`bytes`, encodados na :ref:`codificação do sistema de arquivos " "`." -#: ../../library/asyncio-eventloop.rst:1470 +#: ../../library/asyncio-eventloop.rst:1542 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 +2359,7 @@ msgstr "" "remanescentes especificam os argumentos. Juntas, argumentos em string formam " "o ``argv`` do programa." -#: ../../library/asyncio-eventloop.rst:1474 +#: ../../library/asyncio-eventloop.rst:1546 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 +2372,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:1552 msgid "" "The *protocol_factory* must be a callable returning a subclass of the :class:" "`asyncio.SubprocessProtocol` class." @@ -2263,29 +2380,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:1555 msgid "Other parameters:" msgstr "Outros parâmetros:" -#: ../../library/asyncio-eventloop.rst:1485 +#: ../../library/asyncio-eventloop.rst:1557 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:1559 +#: ../../library/asyncio-eventloop.rst:1570 +#: ../../library/asyncio-eventloop.rst:1580 msgid "a file-like object" msgstr "" -#: ../../library/asyncio-eventloop.rst:1488 +#: ../../library/asyncio-eventloop.rst:1560 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:1561 +#: ../../library/asyncio-eventloop.rst:1571 +#: ../../library/asyncio-eventloop.rst:1581 msgid "" "the :const:`subprocess.PIPE` constant (default) which will create a new pipe " "and connect it," @@ -2293,9 +2410,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:1563 +#: ../../library/asyncio-eventloop.rst:1573 +#: ../../library/asyncio-eventloop.rst:1583 msgid "" "the value ``None`` which will make the subprocess inherit the file " "descriptor from this process" @@ -2303,9 +2420,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:1565 +#: ../../library/asyncio-eventloop.rst:1575 +#: ../../library/asyncio-eventloop.rst:1585 msgid "" "the :const:`subprocess.DEVNULL` constant which indicates that the special :" "data:`os.devnull` file will be used" @@ -2313,15 +2430,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:1568 msgid "*stdout* can be any of these:" msgstr "*stdout* pode ser qualquer um destes:" -#: ../../library/asyncio-eventloop.rst:1506 +#: ../../library/asyncio-eventloop.rst:1578 msgid "*stderr* can be any of these:" msgstr "*stderr* pode ser qualquer um destes:" -#: ../../library/asyncio-eventloop.rst:1515 +#: ../../library/asyncio-eventloop.rst:1587 msgid "" "the :const:`subprocess.STDOUT` constant which will connect the standard " "error stream to the process' standard output stream" @@ -2329,7 +2446,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:1590 msgid "" "All other keyword arguments are passed to :class:`subprocess.Popen` without " "interpretation, except for *bufsize*, *universal_newlines*, *shell*, *text*, " @@ -2340,7 +2457,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:1595 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 +2467,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:1599 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 +2475,7 @@ msgid "" "the event loop." msgstr "" -#: ../../library/asyncio-eventloop.rst:1532 +#: ../../library/asyncio-eventloop.rst:1604 msgid "" "See the constructor of the :class:`subprocess.Popen` class for documentation " "on other arguments." @@ -2366,7 +2483,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:1607 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`asyncio.SubprocessTransport` base class and *protocol* is an " @@ -2376,7 +2493,14 @@ msgstr "" "classe base :class:`asyncio.SubprocessTransport` e *protocol* é um objeto " "instanciado pelo *protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1543 +#: ../../library/asyncio-eventloop.rst:1611 +#: ../../library/asyncio-eventloop.rst:1637 +msgid "" +"If the transport is closed or is garbage collected, the child process is " +"killed if it is still running." +msgstr "" + +#: ../../library/asyncio-eventloop.rst:1619 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:1624 msgid "" "This is similar to the standard library :class:`subprocess.Popen` class " "called with ``shell=True``." msgstr "" "Isto é similar a classe :class:`subprocess.Popen` da biblioteca padrão sendo " -"chanada com ``shell=True``." +"chamada com ``shell=True``." -#: ../../library/asyncio-eventloop.rst:1551 +#: ../../library/asyncio-eventloop.rst:1627 msgid "" "The *protocol_factory* must be a callable returning a subclass of the :class:" "`SubprocessProtocol` class." @@ -2402,7 +2526,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:1630 msgid "" "See :meth:`~loop.subprocess_exec` for more details about the remaining " "arguments." @@ -2410,7 +2534,7 @@ msgstr "" "Veja :meth:`~loop.subprocess_exec` para mais detalhes sobre os argumentos " "remanescentes." -#: ../../library/asyncio-eventloop.rst:1557 +#: ../../library/asyncio-eventloop.rst:1633 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`SubprocessTransport` base class and *protocol* is an object " @@ -2420,7 +2544,7 @@ msgstr "" "classe base :class:`SubprocessTransport` e *protocol* é um objeto " "instanciado pelo *protocol_factory*." -#: ../../library/asyncio-eventloop.rst:1562 +#: ../../library/asyncio-eventloop.rst:1641 msgid "" "It is the application's responsibility to ensure that all whitespace and " "special characters are quoted appropriately to avoid `shell injection " @@ -2436,11 +2560,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:1650 msgid "Callback Handles" msgstr "Tratadores de função de retorno" -#: ../../library/asyncio-eventloop.rst:1575 +#: ../../library/asyncio-eventloop.rst:1654 msgid "" "A callback wrapper object returned by :meth:`loop.call_soon`, :meth:`loop." "call_soon_threadsafe`." @@ -2448,12 +2572,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:1659 msgid "" "Return the :class:`contextvars.Context` object associated with the handle." msgstr "" -#: ../../library/asyncio-eventloop.rst:1587 +#: ../../library/asyncio-eventloop.rst:1666 msgid "" "Cancel the callback. If the callback has already been canceled or executed, " "this method has no effect." @@ -2461,11 +2585,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:1671 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:1677 msgid "" "A callback wrapper object returned by :meth:`loop.call_later`, and :meth:" "`loop.call_at`." @@ -2473,17 +2597,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:1680 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:1684 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:1686 msgid "" "The time is an absolute timestamp, using the same time reference as :meth:" "`loop.time`." @@ -2491,11 +2615,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:1693 msgid "Server Objects" msgstr "Objetos Server" -#: ../../library/asyncio-eventloop.rst:1616 +#: ../../library/asyncio-eventloop.rst:1695 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 +2628,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:1699 msgid "Do not instantiate the :class:`Server` class directly." msgstr "" -#: ../../library/asyncio-eventloop.rst:1624 +#: ../../library/asyncio-eventloop.rst:1703 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 +2643,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:1708 +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:1716 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:1719 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:1724 msgid "" "Stop serving: close listening sockets and set the :attr:`sockets` attribute " "to ``None``." @@ -2538,7 +2678,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:1727 msgid "" "The sockets that represent existing incoming client connections are left " "open." @@ -2546,59 +2686,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:1730 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:1736 msgid "Close all existing incoming client connections." msgstr "" -#: ../../library/asyncio-eventloop.rst:1659 +#: ../../library/asyncio-eventloop.rst:1738 msgid "" "Calls :meth:`~asyncio.BaseTransport.close` on all associated transports." msgstr "" -#: ../../library/asyncio-eventloop.rst:1662 +#: ../../library/asyncio-eventloop.rst:1741 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:1748 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:1751 msgid "" "Calls :meth:`~asyncio.WriteTransport.abort` on all associated transports." msgstr "" -#: ../../library/asyncio-eventloop.rst:1675 +#: ../../library/asyncio-eventloop.rst:1754 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:1761 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:1768 msgid "Start accepting connections." msgstr "Começa a aceitar conexões." -#: ../../library/asyncio-eventloop.rst:1690 +#: ../../library/asyncio-eventloop.rst:1770 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:1773 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 +2752,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:1785 msgid "" "Start accepting connections until the coroutine is cancelled. Cancellation " "of ``serve_forever`` task causes the server to be closed." @@ -2620,7 +2760,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:1789 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 +2768,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:1795 +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:1811 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:1818 msgid "" "Wait until the :meth:`close` method completes and all active connections " "have finished." msgstr "" -#: ../../library/asyncio-eventloop.rst:1741 +#: ../../library/asyncio-eventloop.rst:1823 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:1826 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 +2808,11 @@ msgstr "" "interna de soquetes do server diretamente. No uma cópia dessa lista é " "retornada." -#: ../../library/asyncio-eventloop.rst:1754 +#: ../../library/asyncio-eventloop.rst:1836 msgid "Event Loop Implementations" msgstr "Implementações do Laço de Eventos" -#: ../../library/asyncio-eventloop.rst:1756 +#: ../../library/asyncio-eventloop.rst:1838 msgid "" "asyncio ships with two different event loop implementations: :class:" "`SelectorEventLoop` and :class:`ProactorEventLoop`." @@ -2665,17 +2820,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:1841 msgid "By default asyncio is configured to use :class:`EventLoop`." msgstr "" -#: ../../library/asyncio-eventloop.rst:1764 +#: ../../library/asyncio-eventloop.rst:1846 msgid "" "A subclass of :class:`AbstractEventLoop` based on the :mod:`selectors` " "module." msgstr "" -#: ../../library/asyncio-eventloop.rst:1767 +#: ../../library/asyncio-eventloop.rst:1849 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 +2840,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:1853 +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:1869 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:1875 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:1880 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:1883 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:1889 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:1891 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:1897 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-eventloop.rst:1817 +#: ../../library/asyncio-eventloop.rst:1899 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 +2904,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:1909 msgid "Hello World with call_soon()" msgstr "Hello World com call_soon()" -#: ../../library/asyncio-eventloop.rst:1829 +#: ../../library/asyncio-eventloop.rst:1911 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 +2917,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:1915 +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:1935 msgid "" "A similar :ref:`Hello World ` example created with a coroutine " "and the :func:`run` function." @@ -2767,11 +2946,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:1942 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:1944 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 +2960,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:1948 +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:1972 msgid "" "A similar :ref:`current date ` example created with a " "coroutine and the :func:`run` function." @@ -2789,11 +2993,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:1979 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:1981 msgid "" "Wait until a file descriptor received some data using the :meth:`loop." "add_reader` method and then close the event loop::" @@ -2801,7 +3005,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:1984 +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:2019 msgid "" "A similar :ref:`example ` using " "transports, protocols, and the :meth:`loop.create_connection` method." @@ -2809,7 +3049,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:2023 msgid "" "Another similar :ref:`example ` " "using the high-level :func:`asyncio.open_connection` function and streams." @@ -2817,16 +3057,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:2031 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:2033 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:2035 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:2038 +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..3f843ed9c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..4ebc7b2ba 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..fd04962d1 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -123,31 +120,31 @@ msgid "" "*loop* is not specified and there is no running event loop." msgstr "" -#: ../../library/asyncio-future.rst:79 +#: ../../library/asyncio-future.rst:80 msgid "Future Object" msgstr "" -#: ../../library/asyncio-future.rst:83 +#: ../../library/asyncio-future.rst:84 msgid "" "A Future represents an eventual result of an asynchronous operation. Not " "thread-safe." msgstr "" -#: ../../library/asyncio-future.rst:86 +#: ../../library/asyncio-future.rst:87 msgid "" "Future is an :term:`awaitable` object. Coroutines can await on Future " "objects until they either have a result or an exception set, or until they " "are cancelled. A Future can be awaited multiple times and the result is same." msgstr "" -#: ../../library/asyncio-future.rst:91 +#: ../../library/asyncio-future.rst:92 msgid "" "Typically Futures are used to enable low-level callback-based code (e.g. in " "protocols implemented using asyncio :ref:`transports `) to interoperate with high-level async/await code." msgstr "" -#: ../../library/asyncio-future.rst:96 +#: ../../library/asyncio-future.rst:97 msgid "" "The rule of thumb is to never expose Future objects in user-facing APIs, and " "the recommended way to create a Future object is to call :meth:`loop." @@ -155,11 +152,11 @@ msgid "" "their own optimized implementations of a Future object." msgstr "" -#: ../../library/asyncio-future.rst:102 +#: ../../library/asyncio-future.rst:103 msgid "Added support for the :mod:`contextvars` module." msgstr "Adicionado suporte para o módulo :mod:`contextvars`." -#: ../../library/asyncio-future.rst:105 +#: ../../library/asyncio-future.rst:106 msgid "" "Deprecation warning is emitted if *loop* is not specified and there is no " "running event loop." @@ -167,23 +164,23 @@ msgstr "" "Aviso de descontinuidade é emitido se *loop* não é especificado, e não " "existe nenhum laço de eventos em execução." -#: ../../library/asyncio-future.rst:111 +#: ../../library/asyncio-future.rst:112 msgid "Return the result of the Future." msgstr "" -#: ../../library/asyncio-future.rst:113 +#: ../../library/asyncio-future.rst:114 msgid "" "If the Future is *done* and has a result set by the :meth:`set_result` " "method, the result value is returned." msgstr "" -#: ../../library/asyncio-future.rst:116 +#: ../../library/asyncio-future.rst:117 msgid "" "If the Future is *done* and has an exception set by the :meth:" "`set_exception` method, this method raises the exception." msgstr "" -#: ../../library/asyncio-future.rst:119 ../../library/asyncio-future.rst:207 +#: ../../library/asyncio-future.rst:120 ../../library/asyncio-future.rst:208 msgid "" "If the Future has been *cancelled*, this method raises a :exc:" "`CancelledError` exception." @@ -191,60 +188,66 @@ msgstr "" "Se o futuro foi *cancelled*, este método levanta uma exceção :exc:" "`CancelledError`." -#: ../../library/asyncio-future.rst:122 +#: ../../library/asyncio-future.rst:123 msgid "" "If the Future's result isn't yet available, this method raises an :exc:" "`InvalidStateError` exception." msgstr "" -#: ../../library/asyncio-future.rst:127 +#: ../../library/asyncio-future.rst:128 msgid "Mark the Future as *done* and set its result." msgstr "" -#: ../../library/asyncio-future.rst:129 ../../library/asyncio-future.rst:136 +#: ../../library/asyncio-future.rst:130 ../../library/asyncio-future.rst:137 msgid "" "Raises an :exc:`InvalidStateError` error if the Future is already *done*." msgstr "" -#: ../../library/asyncio-future.rst:134 +#: ../../library/asyncio-future.rst:135 msgid "Mark the Future as *done* and set an exception." msgstr "" -#: ../../library/asyncio-future.rst:141 +#: ../../library/asyncio-future.rst:142 msgid "Return ``True`` if the Future is *done*." msgstr "" -#: ../../library/asyncio-future.rst:143 +#: ../../library/asyncio-future.rst:144 msgid "" "A Future is *done* if it was *cancelled* or if it has a result or an " "exception set with :meth:`set_result` or :meth:`set_exception` calls." msgstr "" -#: ../../library/asyncio-future.rst:149 +#: ../../library/asyncio-future.rst:150 msgid "Return ``True`` if the Future was *cancelled*." msgstr "" -#: ../../library/asyncio-future.rst:151 +#: ../../library/asyncio-future.rst:152 msgid "" "The method is usually used to check if a Future is not *cancelled* before " "setting a result or an exception for it::" msgstr "" -#: ../../library/asyncio-future.rst:159 +#: ../../library/asyncio-future.rst:155 +msgid "" +"if not fut.cancelled():\n" +" fut.set_result(42)" +msgstr "" + +#: ../../library/asyncio-future.rst:160 msgid "Add a callback to be run when the Future is *done*." msgstr "" -#: ../../library/asyncio-future.rst:161 +#: ../../library/asyncio-future.rst:162 msgid "The *callback* is called with the Future object as its only argument." msgstr "" -#: ../../library/asyncio-future.rst:164 +#: ../../library/asyncio-future.rst:165 msgid "" "If the Future is already *done* when this method is called, the callback is " "scheduled with :meth:`loop.call_soon`." msgstr "" -#: ../../library/asyncio-future.rst:167 +#: ../../library/asyncio-future.rst:168 msgid "" "An optional keyword-only *context* argument allows specifying a custom :" "class:`contextvars.Context` for the *callback* to run in. The current " @@ -254,13 +257,20 @@ msgstr "" "class:`contextvars.Context` customizado para executar na *função de " "retorno*. O contexto atual é usado quando nenhum *context* é fornecido." -#: ../../library/asyncio-future.rst:171 +#: ../../library/asyncio-future.rst:172 msgid "" ":func:`functools.partial` can be used to pass parameters to the callback, e." "g.::" msgstr "" -#: ../../library/asyncio-future.rst:178 +#: ../../library/asyncio-future.rst:175 +msgid "" +"# Call 'print(\"Future:\", fut)' when \"fut\" is done.\n" +"fut.add_done_callback(\n" +" functools.partial(print, \"Future:\"))" +msgstr "" + +#: ../../library/asyncio-future.rst:179 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " "details." @@ -268,94 +278,125 @@ msgstr "" "O parâmetro somente-nomeado *context* foi adicionado. Veja :pep:`567` para " "mais detalhes." -#: ../../library/asyncio-future.rst:184 +#: ../../library/asyncio-future.rst:185 msgid "Remove *callback* from the callbacks list." msgstr "Remove *callback* da lista de funções de retorno." -#: ../../library/asyncio-future.rst:186 +#: ../../library/asyncio-future.rst:187 msgid "" "Returns the number of callbacks removed, which is typically 1, unless a " "callback was added more than once." msgstr "" -#: ../../library/asyncio-future.rst:191 +#: ../../library/asyncio-future.rst:192 msgid "Cancel the Future and schedule callbacks." msgstr "" -#: ../../library/asyncio-future.rst:193 +#: ../../library/asyncio-future.rst:194 msgid "" "If the Future is already *done* or *cancelled*, return ``False``. Otherwise, " "change the Future's state to *cancelled*, schedule the callbacks, and return " "``True``." msgstr "" -#: ../../library/asyncio-future.rst:197 +#: ../../library/asyncio-future.rst:198 msgid "Added the *msg* parameter." msgstr "Adicionado o parâmetro *msg*." -#: ../../library/asyncio-future.rst:202 +#: ../../library/asyncio-future.rst:203 msgid "Return the exception that was set on this Future." msgstr "" -#: ../../library/asyncio-future.rst:204 +#: ../../library/asyncio-future.rst:205 msgid "" "The exception (or ``None`` if no exception was set) is returned only if the " "Future is *done*." msgstr "" -#: ../../library/asyncio-future.rst:210 +#: ../../library/asyncio-future.rst:211 msgid "" "If the Future isn't *done* yet, this method raises an :exc:" "`InvalidStateError` exception." msgstr "" -#: ../../library/asyncio-future.rst:215 +#: ../../library/asyncio-future.rst:216 msgid "Return the event loop the Future object is bound to." msgstr "" -#: ../../library/asyncio-future.rst:222 +#: ../../library/asyncio-future.rst:223 msgid "" "This example creates a Future object, creates and schedules an asynchronous " "Task to set result for the Future, and waits until the Future has a result::" msgstr "" -#: ../../library/asyncio-future.rst:257 +#: ../../library/asyncio-future.rst:227 +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:258 msgid "" "The Future object was designed to mimic :class:`concurrent.futures.Future`. " "Key differences include:" msgstr "" -#: ../../library/asyncio-future.rst:260 +#: ../../library/asyncio-future.rst:261 msgid "" "unlike asyncio Futures, :class:`concurrent.futures.Future` instances cannot " "be awaited." msgstr "" -#: ../../library/asyncio-future.rst:263 +#: ../../library/asyncio-future.rst:264 msgid "" ":meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` do not " "accept the *timeout* argument." msgstr "" -#: ../../library/asyncio-future.rst:266 +#: ../../library/asyncio-future.rst:267 msgid "" ":meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` raise an :" "exc:`InvalidStateError` exception when the Future is not *done*." msgstr "" -#: ../../library/asyncio-future.rst:270 +#: ../../library/asyncio-future.rst:271 msgid "" "Callbacks registered with :meth:`asyncio.Future.add_done_callback` are not " "called immediately. They are scheduled with :meth:`loop.call_soon` instead." msgstr "" -#: ../../library/asyncio-future.rst:274 +#: ../../library/asyncio-future.rst:275 msgid "" "asyncio Future is not compatible with the :func:`concurrent.futures.wait` " "and :func:`concurrent.futures.as_completed` functions." msgstr "" -#: ../../library/asyncio-future.rst:278 +#: ../../library/asyncio-future.rst:279 msgid "" ":meth:`asyncio.Future.cancel` accepts an optional ``msg`` argument, but :" "meth:`concurrent.futures.Future.cancel` does not." diff --git a/library/asyncio-llapi-index.po b/library/asyncio-llapi-index.po index 4ddb0354d..bc26455b0 100644 --- a/library/asyncio-llapi-index.po +++ b/library/asyncio-llapi-index.po @@ -1,31 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +128,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." @@ -791,7 +786,7 @@ msgstr "" #: ../../library/asyncio-llapi-index.rst:365 msgid "Return high and low water marks for write flow control." -msgstr "Retorna marcas d'agua alta e baixa para controle do fluxo de escrita." +msgstr "Retorna marcas d'água alta e baixa para controle do fluxo de escrita." #: ../../library/asyncio-llapi-index.rst:367 msgid "" @@ -804,7 +799,7 @@ msgstr "" #: ../../library/asyncio-llapi-index.rst:369 msgid "Set new high and low water marks for write flow control." msgstr "" -"Define novas marcas d'agua alta e baixa para controle do fluxo de escrita." +"Define novas marcas d'água alta e baixa para controle do fluxo de escrita." #: ../../library/asyncio-llapi-index.rst:372 msgid "Transports returned by :meth:`loop.create_datagram_endpoint`:" @@ -937,7 +932,7 @@ msgstr "``callback`` :meth:`pause_writing() `" msgid "Called when the transport's buffer goes over the high water mark." msgstr "" "Chamado quando o buffer de transporte ultrapassa a marca de nível alto " -"d'agua." +"d'água." #: ../../library/asyncio-llapi-index.rst:437 msgid "``callback`` :meth:`resume_writing() `" diff --git a/library/asyncio-platforms.po b/library/asyncio-platforms.po index b78cb082e..6d1058325 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..43505c943 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..7f76ae224 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -532,19 +534,19 @@ msgstr "" #: ../../library/asyncio-protocol.rst:393 msgid "" -"``0``: readable streaming transport of the standard input (*stdin*), or :" +"``0``: writable streaming transport of the standard input (*stdin*), or :" "const:`None` if the subprocess was not created with ``stdin=PIPE``" msgstr "" #: ../../library/asyncio-protocol.rst:395 msgid "" -"``1``: writable streaming transport of the standard output (*stdout*), or :" +"``1``: readable streaming transport of the standard output (*stdout*), or :" "const:`None` if the subprocess was not created with ``stdout=PIPE``" msgstr "" #: ../../library/asyncio-protocol.rst:397 msgid "" -"``2``: writable streaming transport of the standard error (*stderr*), or :" +"``2``: readable streaming transport of the standard error (*stderr*), or :" "const:`None` if the subprocess was not created with ``stderr=PIPE``" 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..641d80294 100644 --- a/library/asyncio-queue.po +++ b/library/asyncio-queue.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +107,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 +120,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 +128,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 +154,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,69 +162,90 @@ 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 "Put a :class:`Queue` instance into a shutdown mode." +msgstr "Coloca uma instância de :class:`Queue` em modo de desligamento." + +#: ../../library/asyncio-queue.rst:107 msgid "" -"Shut down the queue, making :meth:`~Queue.get` and :meth:`~Queue.put` raise :" -"exc:`QueueShutDown`." +"The queue can no longer grow. Future calls to :meth:`~Queue.put` raise :exc:" +"`QueueShutDown`. Currently blocked callers of :meth:`~Queue.put` will be " +"unblocked and will raise :exc:`QueueShutDown` in the formerly blocked thread." msgstr "" -"Desliga a fila, fazendo com que :meth:`~Queue.get` e :meth:`~Queue.put` " -"levantem :exc:`QueueShutDown`." +"A fila não pode mais crescer. Chamadas futuras a :meth:`~Queue.put` " +"levantarão :exc:`QueueShutDown`. Chamadores atualmente bloqueados de :meth:" +"`~Queue.put` serão desbloqueados e levantarão :exc:`QueueShutDown` na thread " +"anteriormente bloqueada." -#: ../../library/asyncio-queue.rst:105 +#: ../../library/asyncio-queue.rst:112 +msgid "" +"If *immediate* is false (the default), the queue can be wound down normally " +"with :meth:`~Queue.get` calls to extract tasks that have already been loaded." +msgstr "" + +#: ../../library/asyncio-queue.rst:116 +msgid "" +"And if :meth:`~Queue.task_done` is called for each remaining task, a " +"pending :meth:`~Queue.join` will be unblocked normally." +msgstr "" + +#: ../../library/asyncio-queue.rst:119 +msgid "" +"Once the queue is empty, future calls to :meth:`~Queue.get` will raise :exc:" +"`QueueShutDown`." +msgstr "" + +#: ../../library/asyncio-queue.rst:122 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 " -"immediately instead." +"If *immediate* is true, the queue is terminated immediately. The queue is " +"drained to be completely empty and the count of unfinished tasks is reduced " +"by the number of tasks drained. If unfinished tasks is zero, callers of :" +"meth:`~Queue.join` are unblocked. Also, blocked callers of :meth:`~Queue." +"get` are unblocked and will raise :exc:`QueueShutDown` because the queue is " +"empty." msgstr "" -"Por padrão, :meth:`~Queue.get` em uma fila de desligamento vai levantar " -"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:130 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 " -"remaining item in the queue, which may unblock callers of :meth:`~Queue." -"join`." +"Use caution when using :meth:`~Queue.join` with *immediate* set to true. " +"This unblocks the join even when no work has been done on the tasks, " +"violating the usual invariant for joining a queue." msgstr "" -"Todos os chamadores bloqueados de :meth:`~Queue.put` e :meth:`~Queue.get` " -"serão desbloqueados. Se *immediate* for verdadeiro, uma tarefa será marcada " -"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:138 +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:140 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:144 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,15 +256,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 -msgid "" -"``shutdown(immediate=True)`` calls :meth:`task_done` for each remaining item " -"in the queue." -msgstr "" -"``shutdown(immediate=True)`` chama :meth:`task_done` para cada item restante " -"na fila." - -#: ../../library/asyncio-queue.rst:132 +#: ../../library/asyncio-queue.rst:149 msgid "" "Raises :exc:`ValueError` if called more times than there were items placed " "in the queue." @@ -255,11 +264,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:154 msgid "Priority Queue" msgstr "Fila de prioridade" -#: ../../library/asyncio-queue.rst:141 +#: ../../library/asyncio-queue.rst:158 msgid "" "A variant of :class:`Queue`; retrieves entries in priority order (lowest " "first)." @@ -267,16 +276,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:161 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:166 msgid "LIFO Queue" msgstr "Filas LIFO (último a entrar, primeiro a sair)" -#: ../../library/asyncio-queue.rst:153 +#: ../../library/asyncio-queue.rst:170 msgid "" "A variant of :class:`Queue` that retrieves most recently added entries first " "(last in, first out)." @@ -284,11 +293,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:175 msgid "Exceptions" msgstr "Exceções" -#: ../../library/asyncio-queue.rst:162 +#: ../../library/asyncio-queue.rst:179 msgid "" "This exception is raised when the :meth:`~Queue.get_nowait` method is called " "on an empty queue." @@ -296,7 +305,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:185 msgid "" "Exception raised when the :meth:`~Queue.put_nowait` method is called on a " "queue that has reached its *maxsize*." @@ -304,7 +313,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:191 msgid "" "Exception raised when :meth:`~Queue.put` or :meth:`~Queue.get` is called on " "a queue which has been shut down." @@ -312,13 +321,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:198 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-queue.rst:185 +#: ../../library/asyncio-queue.rst:202 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:205 +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..909a0da2f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..522447fc8 100644 --- a/library/asyncio-stream.po +++ b/library/asyncio-stream.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-05 14:53+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +48,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:441 +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 +86,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 +94,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 +102,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 +110,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 +118,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:199 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:202 +#: ../../library/asyncio-stream.rst:408 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 +160,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 +170,98 @@ 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:189 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:193 +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 "" +"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-stream.rst:185 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:195 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:205 +msgid "Added the *cleanup_socket* parameter." +msgstr "" + +#: ../../library/asyncio-stream.rst:210 msgid "StreamReader" msgstr "StreamReader" -#: ../../library/asyncio-stream.rst:199 +#: ../../library/asyncio-stream.rst:214 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:218 msgid "" "It is not recommended to instantiate *StreamReader* objects directly; use :" "func:`open_connection` and :func:`start_server` instead." @@ -236,39 +269,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:224 msgid "Acknowledge the EOF." msgstr "" -#: ../../library/asyncio-stream.rst:213 +#: ../../library/asyncio-stream.rst:229 msgid "Read up to *n* bytes from the stream." msgstr "" -#: ../../library/asyncio-stream.rst:215 +#: ../../library/asyncio-stream.rst:231 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:236 msgid "If *n* is ``0``, return an empty ``bytes`` object immediately." msgstr "" -#: ../../library/asyncio-stream.rst:222 +#: ../../library/asyncio-stream.rst:238 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:246 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:249 msgid "" "If EOF is received and ``\\n`` was not found, the method returns partially " "read data." @@ -276,7 +309,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:252 msgid "" "If EOF is received and the internal buffer is empty, return an empty " "``bytes`` object." @@ -284,11 +317,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:258 msgid "Read exactly *n* bytes." msgstr "Lê exatamente *n* bytes." -#: ../../library/asyncio-stream.rst:242 +#: ../../library/asyncio-stream.rst:260 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 +331,11 @@ msgstr "" "lidos. Use o atributo :attr:`IncompleteReadError.partial` para obter os " "dados parcialmente lidos." -#: ../../library/asyncio-stream.rst:248 +#: ../../library/asyncio-stream.rst:267 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:269 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 +343,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:273 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 +353,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:277 msgid "" "If EOF is reached before the complete separator is found, an :exc:" "`IncompleteReadError` exception is raised, and the internal buffer is " @@ -329,10 +362,10 @@ msgid "" msgstr "" "Se EOF for atingido antes que o separador completo seja encontrado, uma " "exceção :exc:`IncompleteReadError` é levantada, e o buffer interno é " -"resetado. O atributo :attr:`IncompleteReadError.partial` pode conter uma " +"redefinido. O atributo :attr:`IncompleteReadError.partial` pode conter uma " "parte do separador." -#: ../../library/asyncio-stream.rst:263 +#: ../../library/asyncio-stream.rst:282 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 +373,27 @@ msgid "" "separator is considered to be the one that matched." msgstr "" -#: ../../library/asyncio-stream.rst:273 +#: ../../library/asyncio-stream.rst:292 msgid "The *separator* parameter may now be a :class:`tuple` of separators." msgstr "" -#: ../../library/asyncio-stream.rst:278 +#: ../../library/asyncio-stream.rst:297 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:302 msgid "StreamWriter" msgstr "StreamWriter" -#: ../../library/asyncio-stream.rst:287 +#: ../../library/asyncio-stream.rst:306 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:309 msgid "" "It is not recommended to instantiate *StreamWriter* objects directly; use :" "func:`open_connection` and :func:`start_server` instead." @@ -368,7 +401,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:315 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 +411,23 @@ 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:319 +msgid "" +"The *data* buffer should be a bytes, bytearray, or C-contiguous one-" +"dimensional memoryview object." +msgstr "" + +#: ../../library/asyncio-stream.rst:322 ../../library/asyncio-stream.rst:335 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:324 +msgid "" +"stream.write(data)\n" +"await stream.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:330 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 +437,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:337 +msgid "" +"stream.writelines(lines)\n" +"await stream.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:342 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:344 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:347 +msgid "" +"stream.close()\n" +"await stream.wait_closed()" +msgstr "" + +#: ../../library/asyncio-stream.rst:352 msgid "" "Return ``True`` if the underlying transport supports the :meth:`write_eof` " "method, ``False`` otherwise." @@ -410,18 +467,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:357 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:362 msgid "Return the underlying asyncio transport." msgstr "Retorna o transporte asyncio subjacente." -#: ../../library/asyncio-stream.rst:343 +#: ../../library/asyncio-stream.rst:366 msgid "" "Access optional transport information; see :meth:`BaseTransport." "get_extra_info` for details." @@ -429,12 +486,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:372 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:375 +msgid "" +"writer.write(data)\n" +"await writer.drain()" +msgstr "" + +#: ../../library/asyncio-stream.rst:378 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()* " @@ -444,23 +507,23 @@ msgid "" msgstr "" "Este é um método de controle de fluxo que interage com o buffer de entrada e " "saída de escrita subjacente. Quando o tamanho do buffer atinge a marca " -"d'agua alta, *drain()* bloqueia até que o tamanho do buffer seja drenado " +"d'água alta, *drain()* bloqueia até que o tamanho do buffer seja drenado " "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:389 msgid "Upgrade an existing stream-based connection to TLS." msgstr "" -#: ../../library/asyncio-stream.rst:366 +#: ../../library/asyncio-stream.rst:391 msgid "Parameters:" msgstr "Parâmetros:" -#: ../../library/asyncio-stream.rst:368 +#: ../../library/asyncio-stream.rst:393 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:395 msgid "" "*server_hostname*: sets or overrides the host name that the target server's " "certificate will be matched against." @@ -468,50 +531,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:398 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:402 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:414 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:422 msgid "Wait until the stream is closed." msgstr "Aguarda até que o stream seja fechado." -#: ../../library/asyncio-stream.rst:398 +#: ../../library/asyncio-stream.rst:424 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:432 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-stream.rst:411 +#: ../../library/asyncio-stream.rst:437 msgid "TCP echo client using streams" msgstr "Cliente para eco TCP usando streams" -#: ../../library/asyncio-stream.rst:413 +#: ../../library/asyncio-stream.rst:439 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:463 msgid "" "The :ref:`TCP echo client protocol " "` example uses the low-level :meth:" @@ -521,15 +584,47 @@ msgstr "" "` usa o método de baixo nível :" "meth:`loop.create_connection`." -#: ../../library/asyncio-stream.rst:444 +#: ../../library/asyncio-stream.rst:470 msgid "TCP echo server using streams" msgstr "Servidor eco TCP usando streams" -#: ../../library/asyncio-stream.rst:446 +#: ../../library/asyncio-stream.rst:472 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:474 +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:506 msgid "" "The :ref:`TCP echo server protocol " "` example uses the :meth:`loop." @@ -539,30 +634,77 @@ msgstr "" "` utiliza o método :meth:`loop." "create_server`." -#: ../../library/asyncio-stream.rst:485 +#: ../../library/asyncio-stream.rst:511 msgid "Get HTTP headers" msgstr "Obtém headers HTTP" -#: ../../library/asyncio-stream.rst:487 +#: ../../library/asyncio-stream.rst:513 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:515 +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:552 msgid "Usage::" msgstr "Uso::" -#: ../../library/asyncio-stream.rst:530 +#: ../../library/asyncio-stream.rst:554 +msgid "python example.py http://example.com/path/page.html" +msgstr "" + +#: ../../library/asyncio-stream.rst:556 msgid "or with HTTPS::" msgstr "ou com HTTPS::" -#: ../../library/asyncio-stream.rst:538 +#: ../../library/asyncio-stream.rst:558 +msgid "python example.py https://example.com/path/page.html" +msgstr "" + +#: ../../library/asyncio-stream.rst:564 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:566 msgid "" "Coroutine waiting until a socket receives data using the :func:" "`open_connection` function::" @@ -570,7 +712,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:569 +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:601 msgid "" "The :ref:`register an open socket to wait for data using a protocol " "` example uses a low-level protocol and " @@ -580,7 +755,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:605 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..3605335d1 100644 --- a/library/asyncio-subprocess.po +++ b/library/asyncio-subprocess.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +52,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 +117,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 +141,59 @@ 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:92 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:96 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:101 +msgid "" +"If the process object is garbage collected while the process is still " +"running, the child process will be killed." +msgstr "" +"Se o objeto do processo for coletado pelo coletor de lixo enquanto o " +"processo ainda estiver em execução, o processo filho será finalizado." + +#: ../../library/asyncio-subprocess.rst:82 +#: ../../library/asyncio-subprocess.rst:113 msgid "Removed the *loop* parameter." msgstr "Removido o parâmetro *loop*." -#: ../../library/asyncio-subprocess.rst:85 +#: ../../library/asyncio-subprocess.rst:90 msgid "Run the *cmd* shell command." msgstr "Executa o comando *cmd* no shell." -#: ../../library/asyncio-subprocess.rst:93 +#: ../../library/asyncio-subprocess.rst:98 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:106 msgid "" "It is the application's responsibility to ensure that all whitespace and " "special characters are quoted appropriately to avoid `shell injection " @@ -138,7 +209,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:118 msgid "" "Subprocesses are available for Windows if a :class:`ProactorEventLoop` is " "used. See :ref:`Subprocess Support on Windows ` " @@ -148,7 +219,7 @@ msgstr "" "`ProactorEventLoop` for usada. Veja :ref:`Suporte para subprocesso para " "Windows ` para detalhes." -#: ../../library/asyncio-subprocess.rst:116 +#: ../../library/asyncio-subprocess.rst:124 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 +233,37 @@ msgstr "" "os :ref:`Transportes de Subprocesso ` e :ref:" "`Protocolos de Subprocesso `." -#: ../../library/asyncio-subprocess.rst:124 +#: ../../library/asyncio-subprocess.rst:132 msgid "Constants" msgstr "Constantes" -#: ../../library/asyncio-subprocess.rst:129 +#: ../../library/asyncio-subprocess.rst:137 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:139 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:143 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:151 msgid "" "Special value that can be used as the *stderr* argument and indicates that " "standard error should be redirected into standard output." @@ -200,7 +271,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:157 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 +282,11 @@ msgstr "" "especial :data:`os.devnull` será usado para o fluxo de subprocesso " "correspondente." -#: ../../library/asyncio-subprocess.rst:155 +#: ../../library/asyncio-subprocess.rst:163 msgid "Interacting with Subprocesses" msgstr "Interagindo com subprocessos" -#: ../../library/asyncio-subprocess.rst:157 +#: ../../library/asyncio-subprocess.rst:165 msgid "" "Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell` " "functions return instances of the *Process* class. *Process* is a high-" @@ -227,15 +298,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:173 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:177 msgid "" "This class is designed to have a similar API to the :class:`subprocess." "Popen` class, but there are some notable differences:" @@ -243,7 +316,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:181 msgid "" "unlike Popen, Process instances do not have an equivalent to the :meth:" "`~subprocess.Popen.poll` method;" @@ -251,7 +324,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:184 msgid "" "the :meth:`~asyncio.subprocess.Process.communicate` and :meth:`~asyncio." "subprocess.Process.wait` methods don't have a *timeout* parameter: use the :" @@ -261,7 +334,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:188 msgid "" "the :meth:`Process.wait() ` method is " "asynchronous, whereas :meth:`subprocess.Popen.wait` method is implemented as " @@ -271,15 +344,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:192 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:194 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:196 msgid "" "See also the :ref:`Subprocess and Threads ` " "section." @@ -287,15 +360,15 @@ msgstr "" "Veja também a seção :ref:`Subprocesso e Threads `." -#: ../../library/asyncio-subprocess.rst:193 +#: ../../library/asyncio-subprocess.rst:202 msgid "Wait for the child process to terminate." msgstr "Aguarda o processo filho encerrar." -#: ../../library/asyncio-subprocess.rst:195 +#: ../../library/asyncio-subprocess.rst:204 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:208 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 +381,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:217 msgid "Interact with process:" msgstr "Interage com processo:" -#: ../../library/asyncio-subprocess.rst:209 +#: ../../library/asyncio-subprocess.rst:219 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:220 msgid "closes *stdin*;" msgstr "fecha *stdin*;" -#: ../../library/asyncio-subprocess.rst:211 +#: ../../library/asyncio-subprocess.rst:221 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:222 msgid "wait for process to terminate." msgstr "aguarda o processo encerrar." -#: ../../library/asyncio-subprocess.rst:214 +#: ../../library/asyncio-subprocess.rst:224 msgid "" "The optional *input* argument is the data (:class:`bytes` object) that will " "be sent to the child process." @@ -338,11 +411,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:227 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:229 msgid "" "If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError` exception is " "raised when writing *input* into *stdin*, the exception is ignored. This " @@ -354,7 +427,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:234 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 +439,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:240 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 +447,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:245 +msgid "*stdin* gets closed when ``input=None`` too." +msgstr "*stdin* é fechado quando ``input=None`` é também." -#: ../../library/asyncio-subprocess.rst:239 +#: ../../library/asyncio-subprocess.rst:249 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:253 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 +466,11 @@ msgstr "" "iniciados com um parâmetro *creationflags*, o qual inclui " "``CREATE_NEW_PROCESS_GROUP``." -#: ../../library/asyncio-subprocess.rst:250 +#: ../../library/asyncio-subprocess.rst:260 msgid "Stop the child process." msgstr "Interrompe o processo filho." -#: ../../library/asyncio-subprocess.rst:252 +#: ../../library/asyncio-subprocess.rst:262 msgid "" "On POSIX systems this method sends :py:const:`~signal.SIGTERM` to the child " "process." @@ -405,7 +478,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:265 msgid "" "On Windows the Win32 API function :c:func:`!TerminateProcess` is called to " "stop the child process." @@ -413,45 +486,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:270 msgid "Kill the child process." msgstr "Mata o processo filho." -#: ../../library/asyncio-subprocess.rst:262 +#: ../../library/asyncio-subprocess.rst:272 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:275 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:279 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:284 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:289 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:294 msgid "" "Use the :meth:`communicate` method rather than :attr:`process.stdin.write() " "`, :attr:`await process.stdout.read() ` or :attr:`await " @@ -463,27 +538,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:303 msgid "Process identification number (PID)." msgstr "Número de identificação do processo (PID)." -#: ../../library/asyncio-subprocess.rst:295 +#: ../../library/asyncio-subprocess.rst:305 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:310 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:312 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:314 msgid "" "A negative value ``-N`` indicates that the child was terminated by signal " "``N`` (POSIX only)." @@ -491,11 +567,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:321 msgid "Subprocess and Threads" msgstr "Subprocesso e Threads" -#: ../../library/asyncio-subprocess.rst:313 +#: ../../library/asyncio-subprocess.rst:323 msgid "" "Standard asyncio event loop supports running subprocesses from different " "threads by default." @@ -503,7 +579,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:326 msgid "" "On Windows subprocesses are provided by :class:`ProactorEventLoop` only " "(default), :class:`SelectorEventLoop` has no subprocess support." @@ -512,7 +588,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:329 msgid "" "On UNIX *child watchers* are used for subprocess finish waiting, see :ref:" "`asyncio-watchers` for more info." @@ -521,7 +597,7 @@ msgstr "" "encerramento de subprocesso, veja :ref:`asyncio-watchers` para mais " "informações." -#: ../../library/asyncio-subprocess.rst:325 +#: ../../library/asyncio-subprocess.rst:335 msgid "" "UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses " "from different threads without any limitation." @@ -529,7 +605,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:338 msgid "" "Spawning a subprocess with *inactive* current child watcher raises :exc:" "`RuntimeError`." @@ -537,7 +613,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:341 msgid "" "Note that alternative event loop implementations might have own limitations; " "please refer to their documentation." @@ -545,7 +621,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:346 msgid "" "The :ref:`Concurrency and multithreading in asyncio ` section." @@ -553,11 +629,11 @@ msgstr "" "A seção :ref:`Concorrência e multithreading em asyncio `." -#: ../../library/asyncio-subprocess.rst:341 +#: ../../library/asyncio-subprocess.rst:351 msgid "Examples" msgstr "Exemplos" -#: ../../library/asyncio-subprocess.rst:343 +#: ../../library/asyncio-subprocess.rst:353 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 +643,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:359 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:362 +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:386 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..cca17f101 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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." +"Subsequent 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..ffebd619a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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:1193 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:1200 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:1141 msgid "Task Object" msgstr "Objeto Task" -#: ../../library/asyncio-task.rst:1093 +#: ../../library/asyncio-task.rst:1145 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:1148 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:1154 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:1159 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:1164 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:1169 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:1174 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:1178 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:1183 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:1190 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:1196 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:1203 msgid "Added the *eager_start* parameter." msgstr "" -#: ../../library/asyncio-task.rst:1156 +#: ../../library/asyncio-task.rst:1208 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:1210 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:1215 msgid "Return the result of the Task." msgstr "Retorna o resultado da Tarefa." -#: ../../library/asyncio-task.rst:1165 +#: ../../library/asyncio-task.rst:1217 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:1221 ../../library/asyncio-task.rst:1235 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:1224 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:1229 msgid "Return the exception of the Task." msgstr "Retorna a exceção de uma Tarefa." -#: ../../library/asyncio-task.rst:1179 +#: ../../library/asyncio-task.rst:1231 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:1238 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:1243 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:1245 ../../library/asyncio-task.rst:1254 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:1247 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:1252 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:1256 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:1261 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:1263 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:1269 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:1271 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:1273 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:1282 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:1284 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:1287 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:1289 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:1294 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:1298 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:1305 msgid "Newly added eager task execution means result may be ``None``." msgstr "" -#: ../../library/asyncio-task.rst:1257 +#: ../../library/asyncio-task.rst:1309 msgid "" "Return the :class:`contextvars.Context` object associated with the task." msgstr "" -#: ../../library/asyncio-task.rst:1264 +#: ../../library/asyncio-task.rst:1316 msgid "Return the name of the Task." msgstr "Retorna o nome da Tarefa." -#: ../../library/asyncio-task.rst:1266 +#: ../../library/asyncio-task.rst:1318 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:1326 msgid "Set the name of the Task." msgstr "Define o nome da Tarefa." -#: ../../library/asyncio-task.rst:1276 +#: ../../library/asyncio-task.rst:1328 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:1331 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:1338 msgid "Request the Task to be cancelled." msgstr "Solicita o cancelamento da Tarefa." -#: ../../library/asyncio-task.rst:1288 +#: ../../library/asyncio-task.rst:1340 msgid "" -"This arranges for a :exc:`CancelledError` exception to be thrown into the " -"wrapped coroutine on the next cycle of the event loop." +"If the Task is already *done* or *cancelled*, return ``False``, otherwise, " +"return ``True``." 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:1343 +msgid "" +"The method arranges for a :exc:`CancelledError` exception to be thrown into " +"the wrapped coroutine on the next cycle of the event loop." +msgstr "" + +#: ../../library/asyncio-task.rst:1346 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:1356 msgid "Added the *msg* parameter." msgstr "Adicionado o parâmetro *msg*." -#: ../../library/asyncio-task.rst:1304 +#: ../../library/asyncio-task.rst:1359 msgid "The ``msg`` parameter is propagated from cancelled task to its awaiter." msgstr "" -#: ../../library/asyncio-task.rst:1309 +#: ../../library/asyncio-task.rst:1364 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:1367 +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:1403 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:1405 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:1411 msgid "Decrement the count of cancellation requests to this Task." msgstr "" -#: ../../library/asyncio-task.rst:1358 +#: ../../library/asyncio-task.rst:1413 msgid "Returns the remaining number of cancellation requests." msgstr "" -#: ../../library/asyncio-task.rst:1360 +#: ../../library/asyncio-task.rst:1415 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:1420 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:1427 +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:1438 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:1444 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:1448 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:1454 msgid "Changed to rescind pending cancellation requests upon reaching zero." msgstr "" -#: ../../library/asyncio-task.rst:1404 +#: ../../library/asyncio-task.rst:1459 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:1463 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:1469 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..2ffd115e5 100644 --- a/library/asyncio.po +++ b/library/asyncio.po @@ -1,40 +1,38 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/asyncio.rst:91 +#: ../../library/asyncio.rst:100 msgid "High-level APIs" msgstr "APIs de alto nível" -#: ../../library/asyncio.rst:103 +#: ../../library/asyncio.rst:112 msgid "Low-level APIs" msgstr "APIs de baixo nível" -#: ../../library/asyncio.rst:114 +#: ../../library/asyncio.rst:123 msgid "Guides and Tutorials" msgstr "Guias e tutoriais" @@ -46,6 +44,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** " @@ -72,11 +90,19 @@ msgstr "" "asyncio geralmente serve perfeitamente para código de rede **estruturado** " "de alto nível e vinculado a E/S." -#: ../../library/asyncio.rst:32 +#: ../../library/asyncio.rst:34 +msgid ":ref:`a-conceptual-overview-of-asyncio`" +msgstr ":ref:`a-conceptual-overview-of-asyncio`" + +#: ../../library/asyncio.rst:35 +msgid "Explanation of the fundamentals of asyncio." +msgstr "Explicação dos fundamentos do asyncio." + +#: ../../library/asyncio.rst:37 msgid "asyncio provides a set of **high-level** APIs to:" msgstr "asyncio fornece um conjunto de APIs de **alto nível** para:" -#: ../../library/asyncio.rst:34 +#: ../../library/asyncio.rst:39 msgid "" ":ref:`run Python coroutines ` concurrently and have full control " "over their execution;" @@ -84,23 +110,23 @@ msgstr "" ":ref:`executar corrotinas do Python ` simultaneamente e ter " "controle total sobre sua execução;" -#: ../../library/asyncio.rst:37 +#: ../../library/asyncio.rst:42 msgid "perform :ref:`network IO and IPC `;" msgstr "realizar :ref:`IPC e E/S de rede `;" -#: ../../library/asyncio.rst:39 +#: ../../library/asyncio.rst:44 msgid "control :ref:`subprocesses `;" msgstr "controlar :ref:`subprocessos `;" -#: ../../library/asyncio.rst:41 +#: ../../library/asyncio.rst:46 msgid "distribute tasks via :ref:`queues `;" msgstr "distribuir tarefas por meio de :ref:`filas `;" -#: ../../library/asyncio.rst:43 +#: ../../library/asyncio.rst:48 msgid ":ref:`synchronize ` concurrent code;" msgstr ":ref:`sincronizar ` código simultâneo;" -#: ../../library/asyncio.rst:45 +#: ../../library/asyncio.rst:50 msgid "" "Additionally, there are **low-level** APIs for *library and framework " "developers* to:" @@ -108,7 +134,7 @@ msgstr "" "Além disso, há APIs de **baixo nível** para *desenvolvedores de biblioteca e " "framework* para:" -#: ../../library/asyncio.rst:48 +#: ../../library/asyncio.rst:53 msgid "" "create and manage :ref:`event loops `, which provide " "asynchronous APIs for :ref:`networking `, running :ref:" @@ -120,7 +146,7 @@ msgstr "" "`subprocessos `, tratamento de :ref:`sinais de " "sistemas operacionais ` etc;" -#: ../../library/asyncio.rst:53 +#: ../../library/asyncio.rst:58 msgid "" "implement efficient protocols using :ref:`transports `;" @@ -128,7 +154,7 @@ msgstr "" "implementar protocolos eficientes usando :ref:`transportes `;" -#: ../../library/asyncio.rst:56 +#: ../../library/asyncio.rst:61 msgid "" ":ref:`bridge ` callback-based libraries and code with async/" "await syntax." @@ -137,8 +163,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 "" @@ -148,18 +174,47 @@ msgstr "" "Este módulo não funciona ou não está disponível em WebAssembly. Veja :ref:" "`wasm-availability` para mais informações." -#: ../../library/asyncio.rst:64 +#: ../../library/asyncio.rst:69 msgid "asyncio REPL" msgstr "REPL de asyncio" -#: ../../library/asyncio.rst:65 +#: ../../library/asyncio.rst:70 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:72 +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 +#: ../../library/asyncio.rst:82 +msgid "" +"This REPL provides limited compatibility with :envvar:`PYTHON_BASIC_REPL`. " +"It is recommended that the default REPL is used for full functionality and " +"the latest features." +msgstr "" +"Este REPL oferece compatibilidade limitada com a variável de ambiente :" +"envvar:`PYTHON_BASIC_REPL`. Recomenda-se o uso do REPL padrão para obter " +"todas as funcionalidades e os recursos mais recentes." + +#: ../../library/asyncio.rst:86 msgid "" "Raises an :ref:`auditing event ` ``cpython.run_stdin`` with no " "arguments." @@ -167,11 +222,11 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``cpython.run_stdin`` sem " "argumentos." -#: ../../library/asyncio.rst:79 +#: ../../library/asyncio.rst:88 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." -#: ../../library/asyncio.rst:82 +#: ../../library/asyncio.rst:91 msgid "" "Uses PyREPL if possible, in which case :envvar:`PYTHONSTARTUP` is also " "executed. Emits audit events." @@ -179,11 +234,11 @@ msgstr "" "Usa PyrePL, se possível, nesse caso :envvar:`PYTHONSTARTUP` também é " "executado. Emite eventos de auditoria." -#: ../../library/asyncio.rst:90 +#: ../../library/asyncio.rst:99 msgid "Reference" msgstr "Referência" -#: ../../library/asyncio.rst:123 +#: ../../library/asyncio.rst:132 msgid "The source code for asyncio can be found in :source:`Lib/asyncio/`." msgstr "" "O código-fonte para o asyncio pode ser encontrado em :source:`Lib/asyncio/`." diff --git a/library/asyncore.po b/library/asyncore.po new file mode 100644 index 000000000..bb76dd058 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..944a59617 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..41cfcd8d6 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..781623404 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..90bffcd5f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..f66e2fdd4 100644 --- a/library/bdb.po +++ b/library/bdb.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 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/bdb.rst:2 msgid ":mod:`!bdb` --- Debugger framework" -msgstr "" +msgstr ":mod:`!bdb` --- Framework do depurador" #: ../../library/bdb.rst:7 msgid "**Source code:** :source:`Lib/bdb.py`" @@ -38,18 +37,20 @@ msgid "" "The :mod:`bdb` module handles basic debugger functions, like setting " "breakpoints or managing execution via the debugger." msgstr "" +"O módulo :mod:`bdb` lida com funções básicas do depurador, como definir " +"pontos de interrupção ou gerenciar a execução por meio do depurador." #: ../../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." -msgstr "" +msgstr "Exceção levantada pela classe :class:`Bdb` para sair do depurador." #: ../../library/bdb.rst:21 msgid "The :mod:`bdb` module also defines two classes:" -msgstr "" +msgstr "O módulo :mod:`bdb` também define duas classes:" #: ../../library/bdb.rst:25 msgid "" @@ -427,7 +428,7 @@ msgid "" ":func:`set_trace` will enter the debugger immediately, rather than on the " "next line of code to be executed." msgstr "" -":func:`set_trace` entrará no depurador imediatamente, em vez de na próxima " +":func:`set_trace` entrará no depurador imediatamente, em vez da próxima " "linha de código a ser executada." #: ../../library/bdb.rst:298 diff --git a/library/binary.po b/library/binary.po index e0e98befa..c5154afd4 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..5e91b18bb 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 similares ` (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..88205f51e 100644 --- a/library/bisect.po +++ b/library/bisect.po @@ -1,32 +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: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2023 +# python-doc bot, 2025 +# 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-09-23 14:56+0000\n" +"PO-Revision-Date: 2025-09-15 01:03+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,12 +54,36 @@ 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 functions in this module are not thread-safe. If multiple threads " +"concurrently use :mod:`bisect` functions on the same sequence, this may " +"result in undefined behaviour. Likewise, if the provided sequence is mutated " +"by a different thread while a :mod:`bisect` function is operating on it, the " +"result is undefined. For example, using :py:func:`~bisect.insort_left` on " +"the same list from multiple threads may result in the list becoming unsorted." +msgstr "" +"As funções neste módulo não são seguras para thread. Se várias threads " +"usarem funções de :mod:`bisect` simultaneamente na mesma sequência, isso " +"poderá resultar em um comportamento indefinido. Da mesma forma, se a " +"sequência fornecida for mutada por uma thread diferente enquanto uma função " +"de :mod:`bisect` estiver operando nela, o resultado será indefinido. Por " +"exemplo, usar :py:func:`~bisect.insort_left` na mesma lista de várias " +"threads pode fazer com que a lista fique desordenada." + +#: ../../library/bisect.rst:39 msgid "The following functions are provided:" msgstr "As seguintes funções são fornecidas:" -#: ../../library/bisect.rst:34 +#: ../../library/bisect.rst:44 msgid "" "Locate the insertion point for *x* in *a* to maintain sorted order. The " "parameters *lo* and *hi* may be used to specify a subset of the list which " @@ -76,7 +100,7 @@ msgstr "" "para uso como o primeiro parâmetro para ``list.insert()`` supondo que *a* já " "esteja ordenado." -#: ../../library/bisect.rst:41 +#: ../../library/bisect.rst:51 msgid "" "The returned insertion point *ip* partitions the array *a* into two slices " "such that ``all(elem < x for elem in a[lo : ip])`` is true for the left " @@ -88,7 +112,7 @@ msgstr "" "fatia esquerda e ``all(elem >= x for elem in a[ip : hi])`` é verdadeiro para " "a fatia certa." -#: ../../library/bisect.rst:46 +#: ../../library/bisect.rst:56 msgid "" "*key* specifies a :term:`key function` of one argument that is used to " "extract a comparison key from each element in the array. To support " @@ -99,7 +123,7 @@ msgstr "" "suporte à pesquisa de registros complexos, a função chave não é aplicada ao " "valor *x*." -#: ../../library/bisect.rst:50 +#: ../../library/bisect.rst:60 msgid "" "If *key* is ``None``, the elements are compared directly and no key function " "is called." @@ -107,12 +131,12 @@ msgstr "" "Se *key* for ``None``, os elementos serão comparados diretamente e nenhuma " "função chave será chamada." -#: ../../library/bisect.rst:53 ../../library/bisect.rst:67 -#: ../../library/bisect.rst:85 ../../library/bisect.rst:105 +#: ../../library/bisect.rst:63 ../../library/bisect.rst:77 +#: ../../library/bisect.rst:95 ../../library/bisect.rst:115 msgid "Added the *key* parameter." msgstr "Adicionado o parâmetro *key*." -#: ../../library/bisect.rst:60 +#: ../../library/bisect.rst:70 msgid "" "Similar to :py:func:`~bisect.bisect_left`, but returns an insertion point " "which comes after (to the right of) any existing entries of *x* in *a*." @@ -121,7 +145,7 @@ msgstr "" "inserção que vem depois (à direita de) qualquer entrada existente de *x* em " "*a*." -#: ../../library/bisect.rst:63 +#: ../../library/bisect.rst:73 msgid "" "The returned insertion point *ip* partitions the array *a* into two slices " "such that ``all(elem <= x for elem in a[lo : ip])`` is true for the left " @@ -133,18 +157,22 @@ msgstr "" "fatia esquerda e ``all(elem > x for elem in a[ip : hi])`` é verdadeiro para " "a fatia certa." -#: ../../library/bisect.rst:73 +#: ../../library/bisect.rst:83 msgid "Insert *x* in *a* in sorted order." msgstr "Insere *x* em *a* na ordem de classificação." -#: ../../library/bisect.rst:75 +#: ../../library/bisect.rst:85 msgid "" "This function first runs :py:func:`~bisect.bisect_left` to locate an " -"insertion point. Next, it runs the :meth:`!insert` method on *a* to insert " -"*x* at the appropriate position to maintain sort order." +"insertion point. Next, it runs the :meth:`~sequence.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, executa o método :meth:`~sequence.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 +#: ../../library/bisect.rst:89 ../../library/bisect.rst:109 msgid "" "To support inserting records in a table, the *key* function (if any) is " "applied to *x* for the search step but not for the insertion step." @@ -153,13 +181,15 @@ msgstr "" "(se houver) é aplicada a *x* para a etapa de pesquisa, mas não para a etapa " "de inserção." -#: ../../library/bisect.rst:82 ../../library/bisect.rst:102 +#: ../../library/bisect.rst:92 ../../library/bisect.rst:112 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 +#: ../../library/bisect.rst:102 msgid "" "Similar to :py:func:`~bisect.insort_left`, but inserting *x* in *a* after " "any existing entries of *x*." @@ -167,18 +197,22 @@ msgstr "" "Semelhante a :py:func:`~bisect.insort_left`, mas inserindo *x* em *a* após " "qualquer entrada existente de *x*." -#: ../../library/bisect.rst:95 +#: ../../library/bisect.rst:105 msgid "" "This function first runs :py:func:`~bisect.bisect_right` to locate an " -"insertion point. Next, it runs the :meth:`!insert` method on *a* to insert " -"*x* at the appropriate position to maintain sort order." +"insertion point. Next, it runs the :meth:`~sequence.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, executa o método :meth:`~sequence.insert` " +"em *a* para inserir *x* na posição apropriada para manter a ordem de " +"classificação." -#: ../../library/bisect.rst:110 +#: ../../library/bisect.rst:120 msgid "Performance Notes" msgstr "Observações sobre desempenho" -#: ../../library/bisect.rst:112 +#: ../../library/bisect.rst:122 msgid "" "When writing time sensitive code using *bisect()* and *insort()*, keep these " "thoughts in mind:" @@ -186,7 +220,7 @@ msgstr "" "Ao escrever um código sensível ao tempo usando *bisect()* e *insort()*, " "lembre-se do seguinte:" -#: ../../library/bisect.rst:115 +#: ../../library/bisect.rst:125 msgid "" "Bisection is effective for searching ranges of values. For locating specific " "values, dictionaries are more performant." @@ -194,13 +228,15 @@ msgstr "" "A bisseção é eficaz para pesquisar intervalos de valores. Para localizar " "valores específicos, os dicionários são mais eficientes." -#: ../../library/bisect.rst:118 +#: ../../library/bisect.rst:128 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 +#: ../../library/bisect.rst:131 msgid "" "The search functions are stateless and discard key function results after " "they are used. Consequently, if the search functions are used in a loop, " @@ -210,15 +246,26 @@ 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 +#: ../../library/bisect.rst:141 msgid "" "`Sorted Collections `_ is a " "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 +#: ../../library/bisect.rst:145 msgid "" "The `SortedCollection recipe `_ uses bisect to build a full-featured collection class " @@ -226,40 +273,236 @@ 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 +#: ../../library/bisect.rst:153 msgid "Searching Sorted Lists" -msgstr "Pesquisando em listas ordenadas" +msgstr "Buscando em listas ordenadas" -#: ../../library/bisect.rst:145 +#: ../../library/bisect.rst:155 msgid "" "The above `bisect functions`_ are useful for finding insertion points but " "can be tricky or awkward to use for common searching tasks. The following " "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:160 +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 +#: ../../library/bisect.rst:197 msgid "Examples" msgstr "Exemplos" -#: ../../library/bisect.rst:191 +#: ../../library/bisect.rst:201 msgid "" "The :py:func:`~bisect.bisect` function can be useful for numeric table " "lookups. This example uses :py:func:`~bisect.bisect` to look up a letter " "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:206 +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 +#: ../../library/bisect.rst:213 msgid "" "The :py:func:`~bisect.bisect` and :py:func:`~bisect.insort` functions also " "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:237 +#: ../../library/bisect.rst:217 +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:247 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:250 +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..a019400e1 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..9cf1f6d5e 100644 --- a/library/bz2.po +++ b/library/bz2.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +224,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." @@ -261,7 +261,7 @@ msgstr "" #: ../../library/bz2.rst:145 msgid "Read bytes into *b*." -msgstr "Lêr bytes para *b*." +msgstr "Lê bytes para *b*." #: ../../library/bz2.rst:147 msgid "Returns the number of bytes read (0 for EOF)." @@ -410,8 +410,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 +426,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 +437,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 +447,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 +461,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 +477,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 +485,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 +493,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..978583650 100644 --- a/library/calendar.po +++ b/library/calendar.po @@ -1,28 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +45,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 +90,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 +146,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 +158,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 +182,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 +194,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 +202,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 +231,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 +312,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 +344,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 +392,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 +677,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, presumindo 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..9ba535c79 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..aedff907c --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..d2632f20d --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..f34b76245 100644 --- a/library/cmath.po +++ b/library/cmath.po @@ -1,29 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-15 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +42,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 +78,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 +94,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 +380,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 +395,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 +403,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 +616,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 +667,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')``." +"``float('nan')``. See also :data:`math.nan`." msgstr "" -"Um valor de ponto flutuante \"não um número\" (NaN). Equivalente a " -"``float('nan')``." +"Um valor de ponto flutuante \"não um número\" (NaN). Equivale a " +"``float('nan')``. Veja também :data:`math.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 +728,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 +748,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 +762,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..46ace2b55 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..ba38ed60d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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: +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..225c2d57c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,19 @@ 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 "" +"Observe que objetos funções e classes criados sob uma instância :class:`!" +"InteractiveInterpreter` pertencerão ao espaço de nomes especificado por " +"*locals*. Só serão selecionáveis se *locals* for o espaço de nomes de um " +"módulo existente." + +#: ../../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 +85,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 +109,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 +132,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 +144,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 +158,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 +172,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 +184,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 +192,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 +204,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 +212,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 +222,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 +232,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 +247,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 +257,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 +265,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 +275,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 +289,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 +305,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 +315,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 +345,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..dceca68a7 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 +# python-doc bot, 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-10-19 14:55+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,17 +76,26 @@ msgid "" "information on codec error handling." msgstr "" -#: ../../library/codecs.rst:56 +#: ../../library/codecs.rst:58 +msgid "" +"Return a mapping suitable for encoding with a custom single-byte encoding. " +"Given a :class:`str` *string* of up to 256 characters representing a " +"decoding table, returns either a compact internal mapping object " +"``EncodingMap`` or a :class:`dictionary ` mapping character ordinals " +"to byte values. Raises a :exc:`TypeError` on invalid input." +msgstr "" + +#: ../../library/codecs.rst:64 msgid "The full details for each codec can also be looked up directly:" msgstr "" -#: ../../library/codecs.rst:60 +#: ../../library/codecs.rst:68 msgid "" "Looks up the codec info in the Python codec registry and returns a :class:" "`CodecInfo` object as defined below." msgstr "" -#: ../../library/codecs.rst:63 +#: ../../library/codecs.rst:71 msgid "" "Encodings are first looked up in the registry's cache. If not found, the " "list of registered search functions is scanned. If no :class:`CodecInfo` " @@ -101,17 +103,17 @@ msgid "" "`CodecInfo` object is stored in the cache and returned to the caller." msgstr "" -#: ../../library/codecs.rst:70 +#: ../../library/codecs.rst:78 msgid "" "Codec details when looking up the codec registry. The constructor arguments " "are stored in attributes of the same name:" msgstr "" -#: ../../library/codecs.rst:76 +#: ../../library/codecs.rst:84 msgid "The name of the encoding." msgstr "" -#: ../../library/codecs.rst:82 +#: ../../library/codecs.rst:90 msgid "" "The stateless encoding and decoding functions. These must be functions or " "methods which have the same interface as the :meth:`~Codec.encode` and :meth:" @@ -120,7 +122,7 @@ msgid "" "mode." msgstr "" -#: ../../library/codecs.rst:92 +#: ../../library/codecs.rst:100 msgid "" "Incremental encoder and decoder classes or factory functions. These have to " "provide the interface defined by the base classes :class:" @@ -128,77 +130,77 @@ msgid "" "Incremental codecs can maintain state." msgstr "" -#: ../../library/codecs.rst:101 +#: ../../library/codecs.rst:109 msgid "" "Stream writer and reader classes or factory functions. These have to provide " "the interface defined by the base classes :class:`StreamWriter` and :class:" "`StreamReader`, respectively. Stream codecs can maintain state." msgstr "" -#: ../../library/codecs.rst:106 +#: ../../library/codecs.rst:114 msgid "" "To simplify access to the various codec components, the module provides " "these additional functions which use :func:`lookup` for the codec lookup:" msgstr "" -#: ../../library/codecs.rst:111 +#: ../../library/codecs.rst:119 msgid "" "Look up the codec for the given encoding and return its encoder function." msgstr "" -#: ../../library/codecs.rst:113 ../../library/codecs.rst:120 -#: ../../library/codecs.rst:146 ../../library/codecs.rst:154 +#: ../../library/codecs.rst:121 ../../library/codecs.rst:128 +#: ../../library/codecs.rst:154 ../../library/codecs.rst:162 msgid "Raises a :exc:`LookupError` in case the encoding cannot be found." msgstr "" -#: ../../library/codecs.rst:118 +#: ../../library/codecs.rst:126 msgid "" "Look up the codec for the given encoding and return its decoder function." msgstr "" -#: ../../library/codecs.rst:125 +#: ../../library/codecs.rst:133 msgid "" "Look up the codec for the given encoding and return its incremental encoder " "class or factory function." msgstr "" -#: ../../library/codecs.rst:128 +#: ../../library/codecs.rst:136 msgid "" "Raises a :exc:`LookupError` in case the encoding cannot be found or the " "codec doesn't support an incremental encoder." msgstr "" -#: ../../library/codecs.rst:134 +#: ../../library/codecs.rst:142 msgid "" "Look up the codec for the given encoding and return its incremental decoder " "class or factory function." msgstr "" -#: ../../library/codecs.rst:137 +#: ../../library/codecs.rst:145 msgid "" "Raises a :exc:`LookupError` in case the encoding cannot be found or the " "codec doesn't support an incremental decoder." msgstr "" -#: ../../library/codecs.rst:143 +#: ../../library/codecs.rst:151 msgid "" "Look up the codec for the given encoding and return its :class:" "`StreamReader` class or factory function." msgstr "" -#: ../../library/codecs.rst:151 +#: ../../library/codecs.rst:159 msgid "" "Look up the codec for the given encoding and return its :class:" "`StreamWriter` class or factory function." msgstr "" -#: ../../library/codecs.rst:156 +#: ../../library/codecs.rst:164 msgid "" "Custom codecs are made available by registering a suitable codec search " "function:" msgstr "" -#: ../../library/codecs.rst:161 +#: ../../library/codecs.rst:169 msgid "" "Register a codec search function. Search functions are expected to take one " "argument, being the encoding name in all lower case letters with hyphens and " @@ -207,17 +209,17 @@ msgid "" "``None``." msgstr "" -#: ../../library/codecs.rst:167 +#: ../../library/codecs.rst:175 msgid "Hyphens and spaces are converted to underscore." msgstr "" -#: ../../library/codecs.rst:173 +#: ../../library/codecs.rst:181 msgid "" "Unregister a codec search function and clear the registry's cache. If the " "search function is not registered, do nothing." msgstr "" -#: ../../library/codecs.rst:179 +#: ../../library/codecs.rst:187 msgid "" "While the builtin :func:`open` and the associated :mod:`io` module are the " "recommended approach for working with encoded text files, this module " @@ -225,14 +227,14 @@ msgid "" "wider range of codecs when working with binary files:" msgstr "" -#: ../../library/codecs.rst:186 +#: ../../library/codecs.rst:194 msgid "" "Open an encoded file using the given *mode* and return an instance of :class:" "`StreamReaderWriter`, providing transparent encoding/decoding. The default " "file mode is ``'r'``, meaning to open the file in read mode." msgstr "" -#: ../../library/codecs.rst:192 +#: ../../library/codecs.rst:200 msgid "" "If *encoding* is not ``None``, then the underlying encoded files are always " "opened in binary mode. No automatic conversion of ``'\\n'`` is done on " @@ -240,38 +242,38 @@ msgid "" "to the built-in :func:`open` function; the ``'b'`` is automatically added." msgstr "" -#: ../../library/codecs.rst:198 +#: ../../library/codecs.rst:206 msgid "" "*encoding* specifies the encoding which is to be used for the file. Any " "encoding that encodes to and decodes from bytes is allowed, and the data " "types supported by the file methods depend on the codec used." msgstr "" -#: ../../library/codecs.rst:202 +#: ../../library/codecs.rst:210 msgid "" "*errors* may be given to define the error handling. It defaults to " "``'strict'`` which causes a :exc:`ValueError` to be raised in case an " "encoding error occurs." msgstr "" -#: ../../library/codecs.rst:205 +#: ../../library/codecs.rst:213 msgid "" "*buffering* has the same meaning as for the built-in :func:`open` function. " "It defaults to -1 which means that the default buffer size will be used." msgstr "" -#: ../../library/codecs.rst:208 +#: ../../library/codecs.rst:216 msgid "The ``'U'`` mode has been removed." msgstr "O modo ``'U'`` foi removido." -#: ../../library/codecs.rst:214 +#: ../../library/codecs.rst:222 msgid "" "Return a :class:`StreamRecoder` instance, a wrapped version of *file* which " "provides transparent transcoding. The original file is closed when the " "wrapped version is closed." msgstr "" -#: ../../library/codecs.rst:218 +#: ../../library/codecs.rst:226 msgid "" "Data written to the wrapped file is decoded according to the given " "*data_encoding* and then written to the original file as bytes using " @@ -279,41 +281,41 @@ msgid "" "*file_encoding*, and the result is encoded using *data_encoding*." msgstr "" -#: ../../library/codecs.rst:224 +#: ../../library/codecs.rst:232 msgid "If *file_encoding* is not given, it defaults to *data_encoding*." msgstr "" -#: ../../library/codecs.rst:226 +#: ../../library/codecs.rst:234 msgid "" "*errors* may be given to define the error handling. It defaults to " "``'strict'``, which causes :exc:`ValueError` to be raised in case an " "encoding error occurs." msgstr "" -#: ../../library/codecs.rst:233 +#: ../../library/codecs.rst:241 msgid "" "Uses an incremental encoder to iteratively encode the input provided by " -"*iterator*. This function is a :term:`generator`. The *errors* argument (as " -"well as any other keyword argument) is passed through to the incremental " -"encoder." +"*iterator*. *iterator* must yield :class:`str` objects. This function is a :" +"term:`generator`. The *errors* argument (as well as any other keyword " +"argument) is passed through to the incremental encoder." msgstr "" -#: ../../library/codecs.rst:238 +#: ../../library/codecs.rst:246 msgid "" "This function requires that the codec accept text :class:`str` objects to " "encode. Therefore it does not support bytes-to-bytes encoders such as " "``base64_codec``." msgstr "" -#: ../../library/codecs.rst:245 +#: ../../library/codecs.rst:253 msgid "" "Uses an incremental decoder to iteratively decode the input provided by " -"*iterator*. This function is a :term:`generator`. The *errors* argument (as " -"well as any other keyword argument) is passed through to the incremental " -"decoder." +"*iterator*. *iterator* must yield :class:`bytes` objects. This function is " +"a :term:`generator`. The *errors* argument (as well as any other keyword " +"argument) is passed through to the incremental decoder." msgstr "" -#: ../../library/codecs.rst:250 +#: ../../library/codecs.rst:258 msgid "" "This function requires that the codec accept :class:`bytes` objects to " "decode. Therefore it does not support text-to-text encoders such as " @@ -321,13 +323,30 @@ msgid "" "`iterencode`." msgstr "" -#: ../../library/codecs.rst:256 +#: ../../library/codecs.rst:266 +msgid "" +"Return a :class:`tuple` containing the raw bytes of *buffer*, a :ref:`buffer-" +"compatible object ` or :class:`str` (encoded to UTF-8 before " +"processing), and their length in bytes." +msgstr "" + +#: ../../library/codecs.rst:270 +msgid "The *errors* argument is ignored." +msgstr "" + +#: ../../library/codecs.rst:272 +msgid "" +">>> codecs.readbuffer_encode(b\"Zito\")\n" +"(b'Zito', 4)" +msgstr "" + +#: ../../library/codecs.rst:278 msgid "" "The module also provides the following constants which are useful for " "reading and writing to platform dependent files:" msgstr "" -#: ../../library/codecs.rst:271 +#: ../../library/codecs.rst:293 msgid "" "These constants define various byte sequences, being Unicode byte order " "marks (BOMs) for several encodings. They are used in UTF-16 and UTF-32 data " @@ -339,18 +358,18 @@ msgid "" "represent the BOM in UTF-8 and UTF-32 encodings." msgstr "" -#: ../../library/codecs.rst:285 +#: ../../library/codecs.rst:307 msgid "Codec Base Classes" msgstr "" -#: ../../library/codecs.rst:287 +#: ../../library/codecs.rst:309 msgid "" "The :mod:`codecs` module defines a set of base classes which define the " "interfaces for working with codec objects, and can also be used as the basis " "for custom codec implementations." msgstr "" -#: ../../library/codecs.rst:291 +#: ../../library/codecs.rst:313 msgid "" "Each codec has to define four interfaces to make it usable as codec in " "Python: stateless encoder, stateless decoder, stream reader and stream " @@ -359,69 +378,69 @@ msgid "" "how the codec will handle encoding and decoding errors." msgstr "" -#: ../../library/codecs.rst:302 +#: ../../library/codecs.rst:324 msgid "Error Handlers" msgstr "" -#: ../../library/codecs.rst:304 +#: ../../library/codecs.rst:326 msgid "" "To simplify and standardize error handling, codecs may implement different " "error handling schemes by accepting the *errors* string argument:" msgstr "" -#: ../../library/codecs.rst:324 +#: ../../library/codecs.rst:346 msgid "" "The following error handlers can be used with all Python :ref:`standard-" "encodings` codecs:" msgstr "" -#: ../../library/codecs.rst:330 ../../library/codecs.rst:373 -#: ../../library/codecs.rst:393 +#: ../../library/codecs.rst:352 ../../library/codecs.rst:395 +#: ../../library/codecs.rst:415 msgid "Value" msgstr "Valor" -#: ../../library/codecs.rst:330 ../../library/codecs.rst:373 -#: ../../library/codecs.rst:393 ../../library/codecs.rst:1331 -#: ../../library/codecs.rst:1399 ../../library/codecs.rst:1454 +#: ../../library/codecs.rst:352 ../../library/codecs.rst:395 +#: ../../library/codecs.rst:415 ../../library/codecs.rst:1365 +#: ../../library/codecs.rst:1437 ../../library/codecs.rst:1522 msgid "Meaning" msgstr "Significado" -#: ../../library/codecs.rst:332 +#: ../../library/codecs.rst:354 msgid "``'strict'``" msgstr "``'strict'``" -#: ../../library/codecs.rst:332 +#: ../../library/codecs.rst:354 msgid "" "Raise :exc:`UnicodeError` (or a subclass), this is the default. Implemented " "in :func:`strict_errors`." msgstr "" -#: ../../library/codecs.rst:336 +#: ../../library/codecs.rst:358 msgid "``'ignore'``" msgstr "``'ignore'``" -#: ../../library/codecs.rst:336 +#: ../../library/codecs.rst:358 msgid "" "Ignore the malformed data and continue without further notice. Implemented " "in :func:`ignore_errors`." msgstr "" -#: ../../library/codecs.rst:340 +#: ../../library/codecs.rst:362 msgid "``'replace'``" msgstr "``'replace'``" -#: ../../library/codecs.rst:340 +#: ../../library/codecs.rst:362 msgid "" "Replace with a replacement marker. On encoding, use ``?`` (ASCII character). " "On decoding, use ``�`` (U+FFFD, the official REPLACEMENT CHARACTER). " "Implemented in :func:`replace_errors`." msgstr "" -#: ../../library/codecs.rst:346 +#: ../../library/codecs.rst:368 msgid "``'backslashreplace'``" msgstr "``'backslashreplace'``" -#: ../../library/codecs.rst:346 +#: ../../library/codecs.rst:368 msgid "" "Replace with backslashed escape sequences. On encoding, use hexadecimal form " "of Unicode code point with formats :samp:`\\\\x{hh}` :samp:`\\\\u{xxxx}` :" @@ -429,11 +448,11 @@ msgid "" "format :samp:`\\\\x{hh}`. Implemented in :func:`backslashreplace_errors`." msgstr "" -#: ../../library/codecs.rst:355 +#: ../../library/codecs.rst:377 msgid "``'surrogateescape'``" msgstr "``'surrogateescape'``" -#: ../../library/codecs.rst:355 +#: ../../library/codecs.rst:377 msgid "" "On decoding, replace byte with individual surrogate code ranging from " "``U+DC80`` to ``U+DCFF``. This code will then be turned back into the same " @@ -441,92 +460,92 @@ msgid "" "data. (See :pep:`383` for more.)" msgstr "" -#: ../../library/codecs.rst:369 +#: ../../library/codecs.rst:391 msgid "" "The following error handlers are only applicable to encoding (within :term:" "`text encodings `):" msgstr "" -#: ../../library/codecs.rst:375 +#: ../../library/codecs.rst:397 msgid "``'xmlcharrefreplace'``" msgstr "``'xmlcharrefreplace'``" -#: ../../library/codecs.rst:375 +#: ../../library/codecs.rst:397 msgid "" "Replace with XML/HTML numeric character reference, which is a decimal form " "of Unicode code point with format :samp:`&#{num};`. Implemented in :func:" "`xmlcharrefreplace_errors`." msgstr "" -#: ../../library/codecs.rst:381 +#: ../../library/codecs.rst:403 msgid "``'namereplace'``" msgstr "``'namereplace'``" -#: ../../library/codecs.rst:381 +#: ../../library/codecs.rst:403 msgid "" "Replace with ``\\N{...}`` escape sequences, what appears in the braces is " "the Name property from Unicode Character Database. Implemented in :func:" "`namereplace_errors`." msgstr "" -#: ../../library/codecs.rst:390 +#: ../../library/codecs.rst:412 msgid "" "In addition, the following error handler is specific to the given codecs:" msgstr "" -#: ../../library/codecs.rst:13 ../../library/codecs.rst:393 +#: ../../library/codecs.rst:13 ../../library/codecs.rst:415 msgid "Codecs" msgstr "Codecs" -#: ../../library/codecs.rst:395 +#: ../../library/codecs.rst:417 msgid "``'surrogatepass'``" msgstr "``'surrogatepass'``" -#: ../../library/codecs.rst:395 +#: ../../library/codecs.rst:417 msgid "utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le" msgstr "" -#: ../../library/codecs.rst:395 +#: ../../library/codecs.rst:417 msgid "" "Allow encoding and decoding surrogate code point (``U+D800`` - ``U+DFFF``) " "as normal code point. Otherwise these codecs treat the presence of surrogate " "code point in :class:`str` as an error." msgstr "" -#: ../../library/codecs.rst:402 +#: ../../library/codecs.rst:424 msgid "The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers." msgstr "" -#: ../../library/codecs.rst:405 +#: ../../library/codecs.rst:427 msgid "" "The ``'surrogatepass'`` error handler now works with utf-16\\* and utf-32\\* " "codecs." msgstr "" -#: ../../library/codecs.rst:409 +#: ../../library/codecs.rst:431 msgid "The ``'namereplace'`` error handler." msgstr "" -#: ../../library/codecs.rst:412 +#: ../../library/codecs.rst:434 msgid "" "The ``'backslashreplace'`` error handler now works with decoding and " "translating." msgstr "" -#: ../../library/codecs.rst:416 +#: ../../library/codecs.rst:438 msgid "" "The set of allowed values can be extended by registering a new named error " "handler:" msgstr "" -#: ../../library/codecs.rst:421 +#: ../../library/codecs.rst:443 msgid "" "Register the error handling function *error_handler* under the name *name*. " "The *error_handler* argument will be called during encoding and decoding in " "case of an error, when *name* is specified as the errors parameter." msgstr "" -#: ../../library/codecs.rst:425 +#: ../../library/codecs.rst:447 msgid "" "For encoding, *error_handler* will be called with a :exc:" "`UnicodeEncodeError` instance, which contains information about the location " @@ -541,66 +560,66 @@ msgid "" "position is out of bound an :exc:`IndexError` will be raised." msgstr "" -#: ../../library/codecs.rst:437 +#: ../../library/codecs.rst:459 msgid "" "Decoding and translating works similarly, except :exc:`UnicodeDecodeError` " "or :exc:`UnicodeTranslateError` will be passed to the handler and that the " "replacement from the error handler will be put into the output directly." msgstr "" -#: ../../library/codecs.rst:442 +#: ../../library/codecs.rst:464 msgid "" "Previously registered error handlers (including the standard error handlers) " "can be looked up by name:" msgstr "" -#: ../../library/codecs.rst:447 +#: ../../library/codecs.rst:469 msgid "Return the error handler previously registered under the name *name*." msgstr "" -#: ../../library/codecs.rst:449 +#: ../../library/codecs.rst:471 msgid "Raises a :exc:`LookupError` in case the handler cannot be found." msgstr "" -#: ../../library/codecs.rst:451 +#: ../../library/codecs.rst:473 msgid "" "The following standard error handlers are also made available as module " "level functions:" msgstr "" -#: ../../library/codecs.rst:456 +#: ../../library/codecs.rst:478 msgid "Implements the ``'strict'`` error handling." msgstr "Implementa a tratativa de erro ``'strict'``." -#: ../../library/codecs.rst:458 +#: ../../library/codecs.rst:480 msgid "Each encoding or decoding error raises a :exc:`UnicodeError`." msgstr "" -#: ../../library/codecs.rst:463 +#: ../../library/codecs.rst:485 msgid "Implements the ``'ignore'`` error handling." msgstr "Implementa a tratativa de erro ``'ignore'``." -#: ../../library/codecs.rst:465 +#: ../../library/codecs.rst:487 msgid "" "Malformed data is ignored; encoding or decoding is continued without further " "notice." msgstr "" -#: ../../library/codecs.rst:471 +#: ../../library/codecs.rst:493 msgid "Implements the ``'replace'`` error handling." msgstr "Implementa a tratativa de erro ``'replace'``." -#: ../../library/codecs.rst:473 +#: ../../library/codecs.rst:495 msgid "" "Substitutes ``?`` (ASCII character) for encoding errors or ``�`` (U+FFFD, " "the official REPLACEMENT CHARACTER) for decoding errors." msgstr "" -#: ../../library/codecs.rst:479 +#: ../../library/codecs.rst:501 msgid "Implements the ``'backslashreplace'`` error handling." msgstr "Implementa a tratativa de erro ``'backslashreplace'``." -#: ../../library/codecs.rst:481 +#: ../../library/codecs.rst:503 msgid "" "Malformed data is replaced by a backslashed escape sequence. On encoding, " "use the hexadecimal form of Unicode code point with formats :samp:`\\\\x{hh}" @@ -608,30 +627,30 @@ msgid "" "hexadecimal form of byte value with format :samp:`\\\\x{hh}`." msgstr "" -#: ../../library/codecs.rst:487 +#: ../../library/codecs.rst:509 msgid "Works with decoding and translating." msgstr "" -#: ../../library/codecs.rst:493 +#: ../../library/codecs.rst:515 msgid "" "Implements the ``'xmlcharrefreplace'`` error handling (for encoding within :" "term:`text encoding` only)." msgstr "" -#: ../../library/codecs.rst:496 +#: ../../library/codecs.rst:518 msgid "" "The unencodable character is replaced by an appropriate XML/HTML numeric " "character reference, which is a decimal form of Unicode code point with " "format :samp:`&#{num};` ." msgstr "" -#: ../../library/codecs.rst:503 +#: ../../library/codecs.rst:525 msgid "" "Implements the ``'namereplace'`` error handling (for encoding within :term:" "`text encoding` only)." msgstr "" -#: ../../library/codecs.rst:506 +#: ../../library/codecs.rst:528 msgid "" "The unencodable character is replaced by a ``\\N{...}`` escape sequence. The " "set of characters that appear in the braces is the Name property from " @@ -639,17 +658,17 @@ msgid "" "will be converted to byte sequence ``\\N{LATIN SMALL LETTER SHARP S}`` ." msgstr "" -#: ../../library/codecs.rst:517 +#: ../../library/codecs.rst:539 msgid "Stateless Encoding and Decoding" msgstr "" -#: ../../library/codecs.rst:519 +#: ../../library/codecs.rst:541 msgid "" "The base :class:`Codec` class defines these methods which also define the " "function interfaces of the stateless encoder and decoder:" msgstr "" -#: ../../library/codecs.rst:527 +#: ../../library/codecs.rst:549 msgid "" "Encodes the object *input* and returns a tuple (output object, length " "consumed). For instance, :term:`text encoding` converts a string object to a " @@ -657,26 +676,26 @@ msgid "" "``iso-8859-1``)." msgstr "" -#: ../../library/codecs.rst:532 ../../library/codecs.rst:554 +#: ../../library/codecs.rst:554 ../../library/codecs.rst:576 msgid "" "The *errors* argument defines the error handling to apply. It defaults to " "``'strict'`` handling." msgstr "" -#: ../../library/codecs.rst:535 +#: ../../library/codecs.rst:557 msgid "" "The method may not store state in the :class:`Codec` instance. Use :class:" "`StreamWriter` for codecs which have to keep state in order to make encoding " "efficient." msgstr "" -#: ../../library/codecs.rst:539 +#: ../../library/codecs.rst:561 msgid "" "The encoder must be able to handle zero length input and return an empty " "object of the output object type in this situation." msgstr "" -#: ../../library/codecs.rst:545 +#: ../../library/codecs.rst:567 msgid "" "Decodes the object *input* and returns a tuple (output object, length " "consumed). For instance, for a :term:`text encoding`, decoding converts a " @@ -684,31 +703,31 @@ msgid "" "object." msgstr "" -#: ../../library/codecs.rst:550 +#: ../../library/codecs.rst:572 msgid "" "For text encodings and bytes-to-bytes codecs, *input* must be a bytes object " "or one which provides the read-only buffer interface -- for example, buffer " "objects and memory mapped files." msgstr "" -#: ../../library/codecs.rst:557 +#: ../../library/codecs.rst:579 msgid "" "The method may not store state in the :class:`Codec` instance. Use :class:" "`StreamReader` for codecs which have to keep state in order to make decoding " "efficient." msgstr "" -#: ../../library/codecs.rst:561 +#: ../../library/codecs.rst:583 msgid "" "The decoder must be able to handle zero length input and return an empty " "object of the output object type in this situation." msgstr "" -#: ../../library/codecs.rst:566 +#: ../../library/codecs.rst:588 msgid "Incremental Encoding and Decoding" msgstr "" -#: ../../library/codecs.rst:568 +#: ../../library/codecs.rst:590 msgid "" "The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes " "provide the basic interface for incremental encoding and decoding. Encoding/" @@ -719,7 +738,7 @@ msgid "" "during method calls." msgstr "" -#: ../../library/codecs.rst:576 +#: ../../library/codecs.rst:598 msgid "" "The joined output of calls to the :meth:`~IncrementalEncoder.encode`/:meth:" "`~IncrementalDecoder.decode` method is the same as if all the single inputs " @@ -727,36 +746,36 @@ msgid "" "encoder/decoder." msgstr "" -#: ../../library/codecs.rst:585 +#: ../../library/codecs.rst:607 msgid "IncrementalEncoder Objects" msgstr "" -#: ../../library/codecs.rst:587 +#: ../../library/codecs.rst:609 msgid "" "The :class:`IncrementalEncoder` class is used for encoding an input in " "multiple steps. It defines the following methods which every incremental " "encoder must define in order to be compatible with the Python codec registry." msgstr "" -#: ../../library/codecs.rst:594 +#: ../../library/codecs.rst:616 msgid "Constructor for an :class:`IncrementalEncoder` instance." msgstr "" -#: ../../library/codecs.rst:596 +#: ../../library/codecs.rst:618 msgid "" "All incremental encoders must provide this constructor interface. They are " "free to add additional keyword arguments, but only the ones defined here are " "used by the Python codec registry." msgstr "" -#: ../../library/codecs.rst:600 +#: ../../library/codecs.rst:622 msgid "" "The :class:`IncrementalEncoder` may implement different error handling " "schemes by providing the *errors* keyword argument. See :ref:`error-" "handlers` for possible values." msgstr "" -#: ../../library/codecs.rst:604 +#: ../../library/codecs.rst:626 msgid "" "The *errors* argument will be assigned to an attribute of the same name. " "Assigning to this attribute makes it possible to switch between different " @@ -764,21 +783,21 @@ msgid "" "`IncrementalEncoder` object." msgstr "" -#: ../../library/codecs.rst:612 +#: ../../library/codecs.rst:634 msgid "" "Encodes *object* (taking the current state of the encoder into account) and " "returns the resulting encoded object. If this is the last call to :meth:" "`encode` *final* must be true (the default is false)." msgstr "" -#: ../../library/codecs.rst:619 +#: ../../library/codecs.rst:641 msgid "" "Reset the encoder to the initial state. The output is discarded: call ``." "encode(object, final=True)``, passing an empty byte or text string if " "necessary, to reset the encoder and to get the output." msgstr "" -#: ../../library/codecs.rst:626 +#: ../../library/codecs.rst:648 msgid "" "Return the current state of the encoder which must be an integer. The " "implementation should make sure that ``0`` is the most common state. (States " @@ -787,42 +806,42 @@ msgid "" "into an integer.)" msgstr "" -#: ../../library/codecs.rst:635 +#: ../../library/codecs.rst:657 msgid "" "Set the state of the encoder to *state*. *state* must be an encoder state " "returned by :meth:`getstate`." msgstr "" -#: ../../library/codecs.rst:642 +#: ../../library/codecs.rst:664 msgid "IncrementalDecoder Objects" msgstr "" -#: ../../library/codecs.rst:644 +#: ../../library/codecs.rst:666 msgid "" "The :class:`IncrementalDecoder` class is used for decoding an input in " "multiple steps. It defines the following methods which every incremental " "decoder must define in order to be compatible with the Python codec registry." msgstr "" -#: ../../library/codecs.rst:651 +#: ../../library/codecs.rst:673 msgid "Constructor for an :class:`IncrementalDecoder` instance." msgstr "" -#: ../../library/codecs.rst:653 +#: ../../library/codecs.rst:675 msgid "" "All incremental decoders must provide this constructor interface. They are " "free to add additional keyword arguments, but only the ones defined here are " "used by the Python codec registry." msgstr "" -#: ../../library/codecs.rst:657 +#: ../../library/codecs.rst:679 msgid "" "The :class:`IncrementalDecoder` may implement different error handling " "schemes by providing the *errors* keyword argument. See :ref:`error-" "handlers` for possible values." msgstr "" -#: ../../library/codecs.rst:661 +#: ../../library/codecs.rst:683 msgid "" "The *errors* argument will be assigned to an attribute of the same name. " "Assigning to this attribute makes it possible to switch between different " @@ -830,7 +849,7 @@ msgid "" "`IncrementalDecoder` object." msgstr "" -#: ../../library/codecs.rst:669 +#: ../../library/codecs.rst:691 msgid "" "Decodes *object* (taking the current state of the decoder into account) and " "returns the resulting decoded object. If this is the last call to :meth:" @@ -841,11 +860,11 @@ msgid "" "(which might raise an exception)." msgstr "" -#: ../../library/codecs.rst:680 +#: ../../library/codecs.rst:702 msgid "Reset the decoder to the initial state." msgstr "" -#: ../../library/codecs.rst:685 +#: ../../library/codecs.rst:707 msgid "" "Return the current state of the decoder. This must be a tuple with two " "items, the first must be the buffer containing the still undecoded input. " @@ -860,59 +879,59 @@ msgid "" "bytes of the resulting string into an integer.)" msgstr "" -#: ../../library/codecs.rst:700 +#: ../../library/codecs.rst:722 msgid "" "Set the state of the decoder to *state*. *state* must be a decoder state " "returned by :meth:`getstate`." msgstr "" -#: ../../library/codecs.rst:705 +#: ../../library/codecs.rst:727 msgid "Stream Encoding and Decoding" msgstr "" -#: ../../library/codecs.rst:708 +#: ../../library/codecs.rst:730 msgid "" "The :class:`StreamWriter` and :class:`StreamReader` classes provide generic " "working interfaces which can be used to implement new encoding submodules " "very easily. See :mod:`!encodings.utf_8` for an example of how this is done." msgstr "" -#: ../../library/codecs.rst:716 +#: ../../library/codecs.rst:738 msgid "StreamWriter Objects" msgstr "" -#: ../../library/codecs.rst:718 +#: ../../library/codecs.rst:740 msgid "" "The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines " "the following methods which every stream writer must define in order to be " "compatible with the Python codec registry." msgstr "" -#: ../../library/codecs.rst:725 +#: ../../library/codecs.rst:747 msgid "Constructor for a :class:`StreamWriter` instance." msgstr "" -#: ../../library/codecs.rst:727 +#: ../../library/codecs.rst:749 msgid "" "All stream writers must provide this constructor interface. They are free to " "add additional keyword arguments, but only the ones defined here are used by " "the Python codec registry." msgstr "" -#: ../../library/codecs.rst:731 +#: ../../library/codecs.rst:753 msgid "" "The *stream* argument must be a file-like object open for writing text or " "binary data, as appropriate for the specific codec." msgstr "" -#: ../../library/codecs.rst:734 +#: ../../library/codecs.rst:756 msgid "" "The :class:`StreamWriter` may implement different error handling schemes by " "providing the *errors* keyword argument. See :ref:`error-handlers` for the " "standard error handlers the underlying stream codec may support." msgstr "" -#: ../../library/codecs.rst:738 +#: ../../library/codecs.rst:760 msgid "" "The *errors* argument will be assigned to an attribute of the same name. " "Assigning to this attribute makes it possible to switch between different " @@ -920,22 +939,22 @@ msgid "" "object." msgstr "" -#: ../../library/codecs.rst:744 +#: ../../library/codecs.rst:766 msgid "Writes the object's contents encoded to the stream." msgstr "" -#: ../../library/codecs.rst:749 +#: ../../library/codecs.rst:771 msgid "" "Writes the concatenated iterable of strings to the stream (possibly by " "reusing the :meth:`write` method). Infinite or very large iterables are not " "supported. The standard bytes-to-bytes codecs do not support this method." msgstr "" -#: ../../library/codecs.rst:757 ../../library/codecs.rst:852 +#: ../../library/codecs.rst:779 ../../library/codecs.rst:874 msgid "Resets the codec buffers used for keeping internal state." msgstr "" -#: ../../library/codecs.rst:759 +#: ../../library/codecs.rst:781 msgid "" "Calling this method should ensure that the data on the output is put into a " "clean state that allows appending of new fresh data without having to rescan " @@ -945,48 +964,48 @@ msgstr "" "limpo, que permite anexar novos dados sem ter que verificar novamente todo o " "fluxo para recuperar o estado." -#: ../../library/codecs.rst:764 +#: ../../library/codecs.rst:786 msgid "" "In addition to the above methods, the :class:`StreamWriter` must also " "inherit all other methods and attributes from the underlying stream." msgstr "" -#: ../../library/codecs.rst:771 +#: ../../library/codecs.rst:793 msgid "StreamReader Objects" msgstr "" -#: ../../library/codecs.rst:773 +#: ../../library/codecs.rst:795 msgid "" "The :class:`StreamReader` class is a subclass of :class:`Codec` and defines " "the following methods which every stream reader must define in order to be " "compatible with the Python codec registry." msgstr "" -#: ../../library/codecs.rst:780 +#: ../../library/codecs.rst:802 msgid "Constructor for a :class:`StreamReader` instance." msgstr "" -#: ../../library/codecs.rst:782 +#: ../../library/codecs.rst:804 msgid "" "All stream readers must provide this constructor interface. They are free to " "add additional keyword arguments, but only the ones defined here are used by " "the Python codec registry." msgstr "" -#: ../../library/codecs.rst:786 +#: ../../library/codecs.rst:808 msgid "" "The *stream* argument must be a file-like object open for reading text or " "binary data, as appropriate for the specific codec." msgstr "" -#: ../../library/codecs.rst:789 +#: ../../library/codecs.rst:811 msgid "" "The :class:`StreamReader` may implement different error handling schemes by " "providing the *errors* keyword argument. See :ref:`error-handlers` for the " "standard error handlers the underlying stream codec may support." msgstr "" -#: ../../library/codecs.rst:793 +#: ../../library/codecs.rst:815 msgid "" "The *errors* argument will be assigned to an attribute of the same name. " "Assigning to this attribute makes it possible to switch between different " @@ -994,24 +1013,24 @@ msgid "" "object." msgstr "" -#: ../../library/codecs.rst:797 +#: ../../library/codecs.rst:819 msgid "" "The set of allowed values for the *errors* argument can be extended with :" "func:`register_error`." msgstr "" -#: ../../library/codecs.rst:803 +#: ../../library/codecs.rst:825 msgid "Decodes data from the stream and returns the resulting object." msgstr "" -#: ../../library/codecs.rst:805 +#: ../../library/codecs.rst:827 msgid "" "The *chars* argument indicates the number of decoded code points or bytes to " "return. The :func:`read` method will never return more data than requested, " "but it might return less, if there is not enough available." msgstr "" -#: ../../library/codecs.rst:810 +#: ../../library/codecs.rst:832 msgid "" "The *size* argument indicates the approximate maximum number of encoded " "bytes or code points to read for decoding. The decoder can modify this " @@ -1020,13 +1039,13 @@ msgid "" "huge files in one step." msgstr "" -#: ../../library/codecs.rst:817 +#: ../../library/codecs.rst:839 msgid "" "The *firstline* flag indicates that it would be sufficient to only return " "the first line, if there are decoding errors on later lines." msgstr "" -#: ../../library/codecs.rst:821 +#: ../../library/codecs.rst:843 msgid "" "The method should use a greedy read strategy meaning that it should read as " "much data as is allowed within the definition of the encoding and the given " @@ -1034,68 +1053,68 @@ msgid "" "the stream, these should be read too." msgstr "" -#: ../../library/codecs.rst:829 +#: ../../library/codecs.rst:851 msgid "Read one line from the input stream and return the decoded data." msgstr "" -#: ../../library/codecs.rst:831 +#: ../../library/codecs.rst:853 msgid "" "*size*, if given, is passed as size argument to the stream's :meth:`read` " "method." msgstr "" -#: ../../library/codecs.rst:834 +#: ../../library/codecs.rst:856 msgid "" "If *keepends* is false line-endings will be stripped from the lines returned." msgstr "" -#: ../../library/codecs.rst:840 +#: ../../library/codecs.rst:862 msgid "" "Read all lines available on the input stream and return them as a list of " "lines." msgstr "" -#: ../../library/codecs.rst:843 +#: ../../library/codecs.rst:865 msgid "" "Line-endings are implemented using the codec's :meth:`decode` method and are " "included in the list entries if *keepends* is true." msgstr "" -#: ../../library/codecs.rst:846 +#: ../../library/codecs.rst:868 msgid "" "*sizehint*, if given, is passed as the *size* argument to the stream's :meth:" "`read` method." msgstr "" -#: ../../library/codecs.rst:854 +#: ../../library/codecs.rst:876 msgid "" "Note that no stream repositioning should take place. This method is " "primarily intended to be able to recover from decoding errors." msgstr "" -#: ../../library/codecs.rst:858 +#: ../../library/codecs.rst:880 msgid "" "In addition to the above methods, the :class:`StreamReader` must also " "inherit all other methods and attributes from the underlying stream." msgstr "" -#: ../../library/codecs.rst:864 +#: ../../library/codecs.rst:886 msgid "StreamReaderWriter Objects" msgstr "" -#: ../../library/codecs.rst:866 +#: ../../library/codecs.rst:888 msgid "" "The :class:`StreamReaderWriter` is a convenience class that allows wrapping " "streams which work in both read and write modes." msgstr "" -#: ../../library/codecs.rst:869 ../../library/codecs.rst:893 +#: ../../library/codecs.rst:891 ../../library/codecs.rst:915 msgid "" "The design is such that one can use the factory functions returned by the :" "func:`lookup` function to construct the instance." msgstr "" -#: ../../library/codecs.rst:875 +#: ../../library/codecs.rst:897 msgid "" "Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like " "object. *Reader* and *Writer* must be factory functions or classes providing " @@ -1104,24 +1123,24 @@ msgid "" "writers." msgstr "" -#: ../../library/codecs.rst:880 +#: ../../library/codecs.rst:902 msgid "" ":class:`StreamReaderWriter` instances define the combined interfaces of :" "class:`StreamReader` and :class:`StreamWriter` classes. They inherit all " "other methods and attributes from the underlying stream." msgstr "" -#: ../../library/codecs.rst:888 +#: ../../library/codecs.rst:910 msgid "StreamRecoder Objects" msgstr "" -#: ../../library/codecs.rst:890 +#: ../../library/codecs.rst:912 msgid "" "The :class:`StreamRecoder` translates data from one encoding to another, " "which is sometimes useful when dealing with different encoding environments." msgstr "" -#: ../../library/codecs.rst:899 +#: ../../library/codecs.rst:921 msgid "" "Creates a :class:`StreamRecoder` instance which implements a two-way " "conversion: *encode* and *decode* work on the frontend — the data visible to " @@ -1129,17 +1148,17 @@ msgid "" "while *Reader* and *Writer* work on the backend — the data in *stream*." msgstr "" -#: ../../library/codecs.rst:905 +#: ../../library/codecs.rst:927 msgid "" "You can use these objects to do transparent transcodings, e.g., from Latin-1 " "to UTF-8 and back." msgstr "" -#: ../../library/codecs.rst:908 +#: ../../library/codecs.rst:930 msgid "The *stream* argument must be a file-like object." msgstr "" -#: ../../library/codecs.rst:910 +#: ../../library/codecs.rst:932 msgid "" "The *encode* and *decode* arguments must adhere to the :class:`Codec` " "interface. *Reader* and *Writer* must be factory functions or classes " @@ -1147,24 +1166,24 @@ msgid "" "interface respectively." msgstr "" -#: ../../library/codecs.rst:915 +#: ../../library/codecs.rst:937 msgid "" "Error handling is done in the same way as defined for the stream readers and " "writers." msgstr "" -#: ../../library/codecs.rst:919 +#: ../../library/codecs.rst:941 msgid "" ":class:`StreamRecoder` instances define the combined interfaces of :class:" "`StreamReader` and :class:`StreamWriter` classes. They inherit all other " "methods and attributes from the underlying stream." msgstr "" -#: ../../library/codecs.rst:927 +#: ../../library/codecs.rst:949 msgid "Encodings and Unicode" msgstr "" -#: ../../library/codecs.rst:929 +#: ../../library/codecs.rst:951 msgid "" "Strings are stored internally as sequences of code points in range " "``U+0000``--``U+10FFFF``. (See :pep:`393` for more details about the " @@ -1176,7 +1195,7 @@ msgid "" "which are collectivity referred to as :term:`text encodings `." msgstr "" -#: ../../library/codecs.rst:939 +#: ../../library/codecs.rst:961 msgid "" "The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps " "the code points 0--255 to the bytes ``0x0``--``0xff``, which means that a " @@ -1187,7 +1206,7 @@ msgid "" "position 3: ordinal not in range(256)``." msgstr "" -#: ../../library/codecs.rst:947 +#: ../../library/codecs.rst:969 msgid "" "There's another group of encodings (the so called charmap encodings) that " "choose a different subset of all Unicode code points and how these code " @@ -1197,37 +1216,45 @@ msgid "" "that shows you which character is mapped to which byte value." msgstr "" -#: ../../library/codecs.rst:954 +#: ../../library/codecs.rst:976 msgid "" "All of these encodings can only encode 256 of the 1114112 code points " "defined in Unicode. A simple and straightforward way that can store each " "Unicode code point, is to store each code point as four consecutive bytes. " "There are two possibilities: store the bytes in big endian or in little " "endian order. These two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` " -"respectively. Their disadvantage is that if e.g. you use ``UTF-32-BE`` on a " -"little endian machine you will always have to swap bytes on encoding and " -"decoding. ``UTF-32`` avoids this problem: bytes will always be in natural " -"endianness. When these bytes are read by a CPU with a different endianness, " -"then bytes have to be swapped though. To be able to detect the endianness of " -"a ``UTF-16`` or ``UTF-32`` byte sequence, there's the so called BOM (\"Byte " -"Order Mark\"). This is the Unicode character ``U+FEFF``. This character can " -"be prepended to every ``UTF-16`` or ``UTF-32`` byte sequence. The byte " -"swapped version of this character (``0xFFFE``) is an illegal character that " -"may not appear in a Unicode text. So when the first character in a " -"``UTF-16`` or ``UTF-32`` byte sequence appears to be a ``U+FFFE`` the bytes " -"have to be swapped on decoding. Unfortunately the character ``U+FEFF`` had a " -"second purpose as a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no " -"width and doesn't allow a word to be split. It can e.g. be used to give " -"hints to a ligature algorithm. With Unicode 4.0 using ``U+FEFF`` as a ``ZERO " -"WIDTH NO-BREAK SPACE`` has been deprecated (with ``U+2060`` (``WORD " -"JOINER``) assuming this role). Nevertheless Unicode software still must be " -"able to handle ``U+FEFF`` in both roles: as a BOM it's a device to determine " -"the storage layout of the encoded bytes, and vanishes once the byte sequence " -"has been decoded into a string; as a ``ZERO WIDTH NO-BREAK SPACE`` it's a " -"normal character that will be decoded like any other." -msgstr "" - -#: ../../library/codecs.rst:980 +"respectively. Their disadvantage is that if, for example, you use ``UTF-32-" +"BE`` on a little endian machine you will always have to swap bytes on " +"encoding and decoding. Python's ``UTF-16`` and ``UTF-32`` codecs avoid this " +"problem by using the platform's native byte order when no BOM is present. " +"Python follows prevailing platform practice, so native-endian data round-" +"trips without redundant byte swapping, even though the Unicode Standard " +"defaults to big-endian when the byte order is unspecified. When these bytes " +"are read by a CPU with a different endianness, the bytes have to be swapped. " +"To be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte " +"sequence, a BOM (\"Byte Order Mark\") is used. This is the Unicode character " +"``U+FEFF``. This character can be prepended to every ``UTF-16`` or " +"``UTF-32`` byte sequence. The byte swapped version of this character " +"(``0xFFFE``) is an illegal character that may not appear in a Unicode text. " +"When the first character of a ``UTF-16`` or ``UTF-32`` byte sequence is " +"``U+FFFE``, the bytes have to be swapped on decoding." +msgstr "" + +#: ../../library/codecs.rst:997 +msgid "" +"Unfortunately the character ``U+FEFF`` had a second purpose as a ``ZERO " +"WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow a " +"word to be split. It can e.g. be used to give hints to a ligature algorithm. " +"With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has " +"been deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). " +"Nevertheless Unicode software still must be able to handle ``U+FEFF`` in " +"both roles: as a BOM it's a device to determine the storage layout of the " +"encoded bytes, and vanishes once the byte sequence has been decoded into a " +"string; as a ``ZERO WIDTH NO-BREAK SPACE`` it's a normal character that will " +"be decoded like any other." +msgstr "" + +#: ../../library/codecs.rst:1007 msgid "" "There's another encoding that is able to encode the full range of Unicode " "characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no " @@ -1238,59 +1265,59 @@ msgid "" "which when concatenated give the Unicode character):" msgstr "" -#: ../../library/codecs.rst:989 +#: ../../library/codecs.rst:1016 msgid "Range" msgstr "" -#: ../../library/codecs.rst:989 +#: ../../library/codecs.rst:1016 msgid "Encoding" msgstr "" -#: ../../library/codecs.rst:991 +#: ../../library/codecs.rst:1018 msgid "``U-00000000`` ... ``U-0000007F``" msgstr "``U-00000000`` ... ``U-0000007F``" -#: ../../library/codecs.rst:991 +#: ../../library/codecs.rst:1018 msgid "0xxxxxxx" msgstr "0xxxxxxx" -#: ../../library/codecs.rst:993 +#: ../../library/codecs.rst:1020 msgid "``U-00000080`` ... ``U-000007FF``" msgstr "``U-00000080`` ... ``U-000007FF``" -#: ../../library/codecs.rst:993 +#: ../../library/codecs.rst:1020 msgid "110xxxxx 10xxxxxx" msgstr "110xxxxx 10xxxxxx" -#: ../../library/codecs.rst:995 +#: ../../library/codecs.rst:1022 msgid "``U-00000800`` ... ``U-0000FFFF``" msgstr "``U-00000800`` ... ``U-0000FFFF``" -#: ../../library/codecs.rst:995 +#: ../../library/codecs.rst:1022 msgid "1110xxxx 10xxxxxx 10xxxxxx" msgstr "1110xxxx 10xxxxxx 10xxxxxx" -#: ../../library/codecs.rst:997 +#: ../../library/codecs.rst:1024 msgid "``U-00010000`` ... ``U-0010FFFF``" msgstr "``U-00010000`` ... ``U-0010FFFF``" -#: ../../library/codecs.rst:997 +#: ../../library/codecs.rst:1024 msgid "11110xxx 10xxxxxx 10xxxxxx 10xxxxxx" msgstr "" -#: ../../library/codecs.rst:1000 +#: ../../library/codecs.rst:1027 msgid "" "The least significant bit of the Unicode character is the rightmost x bit." msgstr "" -#: ../../library/codecs.rst:1002 +#: ../../library/codecs.rst:1029 msgid "" "As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` " "character in the decoded string (even if it's the first character) is " "treated as a ``ZERO WIDTH NO-BREAK SPACE``." msgstr "" -#: ../../library/codecs.rst:1006 +#: ../../library/codecs.rst:1033 msgid "" "Without external information it's impossible to reliably determine which " "encoding was used for encoding a string. Each charmap encoding can decode " @@ -1316,7 +1343,7 @@ msgstr "" msgid "INVERTED QUESTION MARK" msgstr "" -#: ../../library/codecs.rst:1022 +#: ../../library/codecs.rst:1049 msgid "" "in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding " "can be correctly guessed from the byte sequence. So here the BOM is not used " @@ -1328,11 +1355,11 @@ msgid "" "the use of the BOM is discouraged and should generally be avoided." msgstr "" -#: ../../library/codecs.rst:1035 +#: ../../library/codecs.rst:1062 msgid "Standard Encodings" msgstr "" -#: ../../library/codecs.rst:1037 +#: ../../library/codecs.rst:1064 msgid "" "Python comes with a number of codecs built-in, either implemented as C " "functions or with dictionaries as mapping tables. The following table lists " @@ -1340,11 +1367,18 @@ msgid "" "for which the encoding is likely used. Neither the list of aliases nor the " "list of languages is meant to be exhaustive. Notice that spelling " "alternatives that only differ in case or use a hyphen instead of an " -"underscore are also valid aliases; therefore, e.g. ``'utf-8'`` is a valid " -"alias for the ``'utf_8'`` codec." +"underscore are also valid aliases because they are equivalent when " +"normalized by :func:`~encodings.normalize_encoding`. For example, " +"``'utf-8'`` is a valid alias for the ``'utf_8'`` codec." +msgstr "" + +#: ../../library/codecs.rst:1076 +msgid "" +"The below table lists the most common aliases, for a complete list refer to " +"the source :source:`aliases.py ` file." msgstr "" -#: ../../library/codecs.rst:1047 +#: ../../library/codecs.rst:1081 msgid "" "Some common encodings can bypass the codecs lookup machinery to improve " "performance. These optimization opportunities are only recognized by CPython " @@ -1354,11 +1388,11 @@ msgid "" "Using alternative aliases for these encodings may result in slower execution." msgstr "" -#: ../../library/codecs.rst:1055 +#: ../../library/codecs.rst:1089 msgid "Optimization opportunity recognized for us-ascii." msgstr "" -#: ../../library/codecs.rst:1058 +#: ../../library/codecs.rst:1092 msgid "" "Many of the character sets support the same languages. They vary in " "individual characters (e.g. whether the EURO SIGN is supported or not), and " @@ -1366,949 +1400,953 @@ msgid "" "languages in particular, the following variants typically exist:" msgstr "" -#: ../../library/codecs.rst:1063 +#: ../../library/codecs.rst:1097 msgid "an ISO 8859 codeset" msgstr "" -#: ../../library/codecs.rst:1065 +#: ../../library/codecs.rst:1099 msgid "" "a Microsoft Windows code page, which is typically derived from an 8859 " "codeset, but replaces control characters with additional graphic characters" msgstr "" -#: ../../library/codecs.rst:1068 +#: ../../library/codecs.rst:1102 msgid "an IBM EBCDIC code page" msgstr "" -#: ../../library/codecs.rst:1070 +#: ../../library/codecs.rst:1104 msgid "an IBM PC code page, which is ASCII compatible" msgstr "" -#: ../../library/codecs.rst:1075 ../../library/codecs.rst:1331 -#: ../../library/codecs.rst:1399 ../../library/codecs.rst:1454 +#: ../../library/codecs.rst:1109 ../../library/codecs.rst:1365 +#: ../../library/codecs.rst:1437 ../../library/codecs.rst:1522 msgid "Codec" msgstr "" -#: ../../library/codecs.rst:1075 ../../library/codecs.rst:1331 -#: ../../library/codecs.rst:1399 ../../library/codecs.rst:1454 +#: ../../library/codecs.rst:1109 ../../library/codecs.rst:1365 +#: ../../library/codecs.rst:1437 ../../library/codecs.rst:1522 msgid "Aliases" msgstr "" -#: ../../library/codecs.rst:1075 +#: ../../library/codecs.rst:1109 msgid "Languages" msgstr "Idiomas" -#: ../../library/codecs.rst:1077 +#: ../../library/codecs.rst:1111 msgid "ascii" msgstr "ascii" -#: ../../library/codecs.rst:1077 +#: ../../library/codecs.rst:1111 msgid "646, us-ascii" msgstr "646, us-ascii" -#: ../../library/codecs.rst:1077 ../../library/codecs.rst:1083 -#: ../../library/codecs.rst:1091 +#: ../../library/codecs.rst:1111 ../../library/codecs.rst:1117 +#: ../../library/codecs.rst:1125 msgid "English" msgstr "Inglês" -#: ../../library/codecs.rst:1079 +#: ../../library/codecs.rst:1113 msgid "big5" msgstr "big5" -#: ../../library/codecs.rst:1079 +#: ../../library/codecs.rst:1113 msgid "big5-tw, csbig5" msgstr "" -#: ../../library/codecs.rst:1079 ../../library/codecs.rst:1081 -#: ../../library/codecs.rst:1140 +#: ../../library/codecs.rst:1113 ../../library/codecs.rst:1115 +#: ../../library/codecs.rst:1174 msgid "Traditional Chinese" msgstr "" -#: ../../library/codecs.rst:1081 +#: ../../library/codecs.rst:1115 msgid "big5hkscs" msgstr "big5hkscs" -#: ../../library/codecs.rst:1081 +#: ../../library/codecs.rst:1115 msgid "big5-hkscs, hkscs" msgstr "big5-hkscs, hkscs" -#: ../../library/codecs.rst:1083 +#: ../../library/codecs.rst:1117 msgid "cp037" msgstr "cp037" -#: ../../library/codecs.rst:1083 +#: ../../library/codecs.rst:1117 msgid "IBM037, IBM039" msgstr "IBM037, IBM039" -#: ../../library/codecs.rst:1085 +#: ../../library/codecs.rst:1119 msgid "cp273" msgstr "cp273" -#: ../../library/codecs.rst:1085 +#: ../../library/codecs.rst:1119 msgid "273, IBM273, csIBM273" msgstr "273, IBM273, csIBM273" -#: ../../library/codecs.rst:1085 +#: ../../library/codecs.rst:1119 msgid "German" msgstr "Alemão" -#: ../../library/codecs.rst:1089 +#: ../../library/codecs.rst:1123 msgid "cp424" msgstr "cp424" -#: ../../library/codecs.rst:1089 +#: ../../library/codecs.rst:1123 msgid "EBCDIC-CP-HE, IBM424" msgstr "EBCDIC-CP-HE, IBM424" -#: ../../library/codecs.rst:1089 ../../library/codecs.rst:1109 -#: ../../library/codecs.rst:1119 ../../library/codecs.rst:1163 -#: ../../library/codecs.rst:1226 +#: ../../library/codecs.rst:1123 ../../library/codecs.rst:1143 +#: ../../library/codecs.rst:1153 ../../library/codecs.rst:1197 +#: ../../library/codecs.rst:1260 msgid "Hebrew" msgstr "Hebraico" -#: ../../library/codecs.rst:1091 +#: ../../library/codecs.rst:1125 msgid "cp437" msgstr "cp437" -#: ../../library/codecs.rst:1091 +#: ../../library/codecs.rst:1125 msgid "437, IBM437" msgstr "437, IBM437" -#: ../../library/codecs.rst:1093 +#: ../../library/codecs.rst:1127 msgid "cp500" msgstr "cp500" -#: ../../library/codecs.rst:1093 +#: ../../library/codecs.rst:1127 msgid "EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500" msgstr "EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500" -#: ../../library/codecs.rst:1093 ../../library/codecs.rst:1102 -#: ../../library/codecs.rst:1113 ../../library/codecs.rst:1150 -#: ../../library/codecs.rst:1157 ../../library/codecs.rst:1210 -#: ../../library/codecs.rst:1238 ../../library/codecs.rst:1266 +#: ../../library/codecs.rst:1127 ../../library/codecs.rst:1136 +#: ../../library/codecs.rst:1147 ../../library/codecs.rst:1184 +#: ../../library/codecs.rst:1191 ../../library/codecs.rst:1244 +#: ../../library/codecs.rst:1272 ../../library/codecs.rst:1300 msgid "Western Europe" msgstr "" -#: ../../library/codecs.rst:1096 +#: ../../library/codecs.rst:1130 msgid "cp720" msgstr "cp720" -#: ../../library/codecs.rst:1096 ../../library/codecs.rst:1123 -#: ../../library/codecs.rst:1165 ../../library/codecs.rst:1222 +#: ../../library/codecs.rst:1130 ../../library/codecs.rst:1157 +#: ../../library/codecs.rst:1199 ../../library/codecs.rst:1256 msgid "Arabic" msgstr "Árabe" -#: ../../library/codecs.rst:1098 +#: ../../library/codecs.rst:1132 msgid "cp737" msgstr "cp737" -#: ../../library/codecs.rst:1098 ../../library/codecs.rst:1129 -#: ../../library/codecs.rst:1133 ../../library/codecs.rst:1159 -#: ../../library/codecs.rst:1224 ../../library/codecs.rst:1259 +#: ../../library/codecs.rst:1132 ../../library/codecs.rst:1163 +#: ../../library/codecs.rst:1167 ../../library/codecs.rst:1193 +#: ../../library/codecs.rst:1258 ../../library/codecs.rst:1293 msgid "Greek" msgstr "Grego" -#: ../../library/codecs.rst:1100 +#: ../../library/codecs.rst:1134 msgid "cp775" msgstr "cp775" -#: ../../library/codecs.rst:1100 +#: ../../library/codecs.rst:1134 msgid "IBM775" msgstr "IBM775" -#: ../../library/codecs.rst:1100 ../../library/codecs.rst:1167 -#: ../../library/codecs.rst:1217 ../../library/codecs.rst:1234 +#: ../../library/codecs.rst:1134 ../../library/codecs.rst:1201 +#: ../../library/codecs.rst:1268 msgid "Baltic languages" msgstr "" -#: ../../library/codecs.rst:1102 +#: ../../library/codecs.rst:1136 msgid "cp850" msgstr "cp850" -#: ../../library/codecs.rst:1102 +#: ../../library/codecs.rst:1136 msgid "850, IBM850" msgstr "850, IBM850" -#: ../../library/codecs.rst:1104 +#: ../../library/codecs.rst:1138 msgid "cp852" msgstr "cp852" -#: ../../library/codecs.rst:1104 +#: ../../library/codecs.rst:1138 msgid "852, IBM852" msgstr "852, IBM852" -#: ../../library/codecs.rst:1104 ../../library/codecs.rst:1152 -#: ../../library/codecs.rst:1213 ../../library/codecs.rst:1263 +#: ../../library/codecs.rst:1138 ../../library/codecs.rst:1186 +#: ../../library/codecs.rst:1247 ../../library/codecs.rst:1297 msgid "Central and Eastern Europe" msgstr "" -#: ../../library/codecs.rst:1106 +#: ../../library/codecs.rst:1140 msgid "cp855" msgstr "cp855" -#: ../../library/codecs.rst:1106 +#: ../../library/codecs.rst:1140 msgid "855, IBM855" 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" +#: ../../library/codecs.rst:1140 ../../library/codecs.rst:1188 +#: ../../library/codecs.rst:1253 ../../library/codecs.rst:1290 +msgid "Belarusian, Bulgarian, Macedonian, Russian, Serbian" msgstr "" -#: ../../library/codecs.rst:1109 +#: ../../library/codecs.rst:1143 msgid "cp856" msgstr "cp856" -#: ../../library/codecs.rst:1111 +#: ../../library/codecs.rst:1145 msgid "cp857" msgstr "cp857" -#: ../../library/codecs.rst:1111 +#: ../../library/codecs.rst:1145 msgid "857, IBM857" msgstr "857, IBM857" -#: ../../library/codecs.rst:1111 ../../library/codecs.rst:1144 -#: ../../library/codecs.rst:1161 ../../library/codecs.rst:1228 -#: ../../library/codecs.rst:1268 +#: ../../library/codecs.rst:1145 ../../library/codecs.rst:1178 +#: ../../library/codecs.rst:1195 ../../library/codecs.rst:1262 +#: ../../library/codecs.rst:1302 msgid "Turkish" msgstr "Turco" -#: ../../library/codecs.rst:1113 +#: ../../library/codecs.rst:1147 msgid "cp858" msgstr "cp858" -#: ../../library/codecs.rst:1113 +#: ../../library/codecs.rst:1147 msgid "858, IBM858" msgstr "858, IBM858" -#: ../../library/codecs.rst:1115 +#: ../../library/codecs.rst:1149 msgid "cp860" msgstr "cp860" -#: ../../library/codecs.rst:1115 +#: ../../library/codecs.rst:1149 msgid "860, IBM860" msgstr "860, IBM860" -#: ../../library/codecs.rst:1115 +#: ../../library/codecs.rst:1149 msgid "Portuguese" msgstr "Português" -#: ../../library/codecs.rst:1117 +#: ../../library/codecs.rst:1151 msgid "cp861" msgstr "cp861" -#: ../../library/codecs.rst:1117 +#: ../../library/codecs.rst:1151 msgid "861, CP-IS, IBM861" msgstr "861, CP-IS, IBM861" -#: ../../library/codecs.rst:1117 ../../library/codecs.rst:1261 +#: ../../library/codecs.rst:1151 ../../library/codecs.rst:1295 msgid "Icelandic" msgstr "Islandês" -#: ../../library/codecs.rst:1119 +#: ../../library/codecs.rst:1153 msgid "cp862" msgstr "cp862" -#: ../../library/codecs.rst:1119 +#: ../../library/codecs.rst:1153 msgid "862, IBM862" msgstr "862, IBM862" -#: ../../library/codecs.rst:1121 +#: ../../library/codecs.rst:1155 msgid "cp863" msgstr "cp863" -#: ../../library/codecs.rst:1121 +#: ../../library/codecs.rst:1155 msgid "863, IBM863" msgstr "863, IBM863" -#: ../../library/codecs.rst:1121 +#: ../../library/codecs.rst:1155 msgid "Canadian" msgstr "Canadense" -#: ../../library/codecs.rst:1123 +#: ../../library/codecs.rst:1157 msgid "cp864" msgstr "cp864" -#: ../../library/codecs.rst:1123 +#: ../../library/codecs.rst:1157 msgid "IBM864" msgstr "IBM864" -#: ../../library/codecs.rst:1125 +#: ../../library/codecs.rst:1159 msgid "cp865" msgstr "cp865" -#: ../../library/codecs.rst:1125 +#: ../../library/codecs.rst:1159 msgid "865, IBM865" msgstr "865, IBM865" -#: ../../library/codecs.rst:1125 +#: ../../library/codecs.rst:1159 msgid "Danish, Norwegian" msgstr "" -#: ../../library/codecs.rst:1127 +#: ../../library/codecs.rst:1161 msgid "cp866" msgstr "cp866" -#: ../../library/codecs.rst:1127 +#: ../../library/codecs.rst:1161 msgid "866, IBM866" msgstr "866, IBM866" -#: ../../library/codecs.rst:1127 ../../library/codecs.rst:1244 +#: ../../library/codecs.rst:1161 ../../library/codecs.rst:1278 msgid "Russian" msgstr "Russo" -#: ../../library/codecs.rst:1129 +#: ../../library/codecs.rst:1163 msgid "cp869" msgstr "cp869" -#: ../../library/codecs.rst:1129 +#: ../../library/codecs.rst:1163 msgid "869, CP-GR, IBM869" msgstr "869, CP-GR, IBM869" -#: ../../library/codecs.rst:1131 +#: ../../library/codecs.rst:1165 msgid "cp874" msgstr "cp874" -#: ../../library/codecs.rst:1131 +#: ../../library/codecs.rst:1165 msgid "Thai" msgstr "Tailandês" -#: ../../library/codecs.rst:1133 +#: ../../library/codecs.rst:1167 msgid "cp875" msgstr "cp875" -#: ../../library/codecs.rst:1135 +#: ../../library/codecs.rst:1169 msgid "cp932" msgstr "cp932" -#: ../../library/codecs.rst:1135 +#: ../../library/codecs.rst:1169 msgid "932, ms932, mskanji, ms-kanji, windows-31j" msgstr "" -#: ../../library/codecs.rst:1135 ../../library/codecs.rst:1171 -#: ../../library/codecs.rst:1173 ../../library/codecs.rst:1175 -#: ../../library/codecs.rst:1192 ../../library/codecs.rst:1195 -#: ../../library/codecs.rst:1200 ../../library/codecs.rst:1203 -#: ../../library/codecs.rst:1205 ../../library/codecs.rst:1273 -#: ../../library/codecs.rst:1276 ../../library/codecs.rst:1279 +#: ../../library/codecs.rst:1169 ../../library/codecs.rst:1205 +#: ../../library/codecs.rst:1207 ../../library/codecs.rst:1209 +#: ../../library/codecs.rst:1226 ../../library/codecs.rst:1229 +#: ../../library/codecs.rst:1234 ../../library/codecs.rst:1237 +#: ../../library/codecs.rst:1239 ../../library/codecs.rst:1307 +#: ../../library/codecs.rst:1310 ../../library/codecs.rst:1313 msgid "Japanese" msgstr "Japonês" -#: ../../library/codecs.rst:1138 +#: ../../library/codecs.rst:1172 msgid "cp949" msgstr "cp949" -#: ../../library/codecs.rst:1138 +#: ../../library/codecs.rst:1172 msgid "949, ms949, uhc" msgstr "949, ms949, uhc" -#: ../../library/codecs.rst:1138 ../../library/codecs.rst:1177 -#: ../../library/codecs.rst:1207 ../../library/codecs.rst:1242 +#: ../../library/codecs.rst:1172 ../../library/codecs.rst:1211 +#: ../../library/codecs.rst:1241 ../../library/codecs.rst:1276 msgid "Korean" msgstr "Coreano" -#: ../../library/codecs.rst:1140 +#: ../../library/codecs.rst:1174 msgid "cp950" msgstr "cp950" -#: ../../library/codecs.rst:1140 +#: ../../library/codecs.rst:1174 msgid "950, ms950" msgstr "950, ms950" -#: ../../library/codecs.rst:1142 +#: ../../library/codecs.rst:1176 msgid "cp1006" msgstr "cp1006" -#: ../../library/codecs.rst:1142 +#: ../../library/codecs.rst:1176 msgid "Urdu" msgstr "" -#: ../../library/codecs.rst:1144 +#: ../../library/codecs.rst:1178 msgid "cp1026" msgstr "cp1026" -#: ../../library/codecs.rst:1144 +#: ../../library/codecs.rst:1178 msgid "ibm1026" msgstr "ibm1026" -#: ../../library/codecs.rst:1146 +#: ../../library/codecs.rst:1180 msgid "cp1125" msgstr "cp1125" -#: ../../library/codecs.rst:1146 +#: ../../library/codecs.rst:1180 msgid "1125, ibm1125, cp866u, ruscii" msgstr "" -#: ../../library/codecs.rst:1146 ../../library/codecs.rst:1250 +#: ../../library/codecs.rst:1180 ../../library/codecs.rst:1284 msgid "Ukrainian" msgstr "Ucraniano" -#: ../../library/codecs.rst:1150 +#: ../../library/codecs.rst:1184 msgid "cp1140" msgstr "cp1140" -#: ../../library/codecs.rst:1150 +#: ../../library/codecs.rst:1184 msgid "ibm1140" msgstr "ibm1140" -#: ../../library/codecs.rst:1152 +#: ../../library/codecs.rst:1186 msgid "cp1250" msgstr "cp1250" -#: ../../library/codecs.rst:1152 +#: ../../library/codecs.rst:1186 msgid "windows-1250" msgstr "windows-1250" -#: ../../library/codecs.rst:1154 +#: ../../library/codecs.rst:1188 msgid "cp1251" msgstr "cp1251" -#: ../../library/codecs.rst:1154 +#: ../../library/codecs.rst:1188 msgid "windows-1251" msgstr "windows-1251" -#: ../../library/codecs.rst:1157 +#: ../../library/codecs.rst:1191 msgid "cp1252" msgstr "cp1252" -#: ../../library/codecs.rst:1157 +#: ../../library/codecs.rst:1191 msgid "windows-1252" msgstr "windows-1252" -#: ../../library/codecs.rst:1159 +#: ../../library/codecs.rst:1193 msgid "cp1253" msgstr "cp1253" -#: ../../library/codecs.rst:1159 +#: ../../library/codecs.rst:1193 msgid "windows-1253" msgstr "windows-1253" -#: ../../library/codecs.rst:1161 +#: ../../library/codecs.rst:1195 msgid "cp1254" msgstr "cp1254" -#: ../../library/codecs.rst:1161 +#: ../../library/codecs.rst:1195 msgid "windows-1254" msgstr "windows-1254" -#: ../../library/codecs.rst:1163 +#: ../../library/codecs.rst:1197 msgid "cp1255" msgstr "cp1255" -#: ../../library/codecs.rst:1163 +#: ../../library/codecs.rst:1197 msgid "windows-1255" msgstr "windows-1255" -#: ../../library/codecs.rst:1165 +#: ../../library/codecs.rst:1199 msgid "cp1256" msgstr "cp1256" -#: ../../library/codecs.rst:1165 +#: ../../library/codecs.rst:1199 msgid "windows-1256" msgstr "windows-1256" -#: ../../library/codecs.rst:1167 +#: ../../library/codecs.rst:1201 msgid "cp1257" msgstr "cp1257" -#: ../../library/codecs.rst:1167 +#: ../../library/codecs.rst:1201 msgid "windows-1257" msgstr "windows-1257" -#: ../../library/codecs.rst:1169 +#: ../../library/codecs.rst:1203 msgid "cp1258" msgstr "cp1258" -#: ../../library/codecs.rst:1169 +#: ../../library/codecs.rst:1203 msgid "windows-1258" msgstr "windows-1258" -#: ../../library/codecs.rst:1169 +#: ../../library/codecs.rst:1203 msgid "Vietnamese" msgstr "Vietnamita" -#: ../../library/codecs.rst:1171 +#: ../../library/codecs.rst:1205 msgid "euc_jp" msgstr "euc_jp" -#: ../../library/codecs.rst:1171 +#: ../../library/codecs.rst:1205 msgid "eucjp, ujis, u-jis" msgstr "eucjp, ujis, u-jis" -#: ../../library/codecs.rst:1173 +#: ../../library/codecs.rst:1207 msgid "euc_jis_2004" msgstr "euc_jis_2004" -#: ../../library/codecs.rst:1173 +#: ../../library/codecs.rst:1207 msgid "jisx0213, eucjis2004" msgstr "jisx0213, eucjis2004" -#: ../../library/codecs.rst:1175 +#: ../../library/codecs.rst:1209 msgid "euc_jisx0213" msgstr "euc_jisx0213" -#: ../../library/codecs.rst:1175 +#: ../../library/codecs.rst:1209 msgid "eucjisx0213" msgstr "eucjisx0213" -#: ../../library/codecs.rst:1177 +#: ../../library/codecs.rst:1211 msgid "euc_kr" msgstr "euc_kr" -#: ../../library/codecs.rst:1177 +#: ../../library/codecs.rst:1211 msgid "euckr, korean, ksc5601, ks_c-5601, ks_c-5601-1987, ksx1001, ks_x-1001" msgstr "" -#: ../../library/codecs.rst:1181 +#: ../../library/codecs.rst:1215 msgid "gb2312" msgstr "gb2312" -#: ../../library/codecs.rst:1181 +#: ../../library/codecs.rst:1215 msgid "" "chinese, csiso58gb231280, euc-cn, euccn, eucgb2312-cn, gb2312-1980, " "gb2312-80, iso-ir-58" msgstr "" -#: ../../library/codecs.rst:1181 ../../library/codecs.rst:1190 +#: ../../library/codecs.rst:1215 ../../library/codecs.rst:1224 msgid "Simplified Chinese" msgstr "" -#: ../../library/codecs.rst:1186 +#: ../../library/codecs.rst:1220 msgid "gbk" msgstr "gbk" -#: ../../library/codecs.rst:1186 +#: ../../library/codecs.rst:1220 msgid "936, cp936, ms936" msgstr "936, cp936, ms936" -#: ../../library/codecs.rst:1186 ../../library/codecs.rst:1188 +#: ../../library/codecs.rst:1220 ../../library/codecs.rst:1222 msgid "Unified Chinese" msgstr "" -#: ../../library/codecs.rst:1188 +#: ../../library/codecs.rst:1222 msgid "gb18030" msgstr "gb18030" -#: ../../library/codecs.rst:1188 +#: ../../library/codecs.rst:1222 msgid "gb18030-2000" msgstr "gb18030-2000" -#: ../../library/codecs.rst:1190 +#: ../../library/codecs.rst:1224 msgid "hz" msgstr "hz" -#: ../../library/codecs.rst:1190 +#: ../../library/codecs.rst:1224 msgid "hzgb, hz-gb, hz-gb-2312" msgstr "hzgb, hz-gb, hz-gb-2312" -#: ../../library/codecs.rst:1192 +#: ../../library/codecs.rst:1226 msgid "iso2022_jp" msgstr "iso2022_jp" -#: ../../library/codecs.rst:1192 +#: ../../library/codecs.rst:1226 msgid "csiso2022jp, iso2022jp, iso-2022-jp" msgstr "csiso2022jp, iso2022jp, iso-2022-jp" -#: ../../library/codecs.rst:1195 +#: ../../library/codecs.rst:1229 msgid "iso2022_jp_1" msgstr "iso2022_jp_1" -#: ../../library/codecs.rst:1195 +#: ../../library/codecs.rst:1229 msgid "iso2022jp-1, iso-2022-jp-1" msgstr "iso2022jp-1, iso-2022-jp-1" -#: ../../library/codecs.rst:1197 +#: ../../library/codecs.rst:1231 msgid "iso2022_jp_2" msgstr "iso2022_jp_2" -#: ../../library/codecs.rst:1197 +#: ../../library/codecs.rst:1231 msgid "iso2022jp-2, iso-2022-jp-2" msgstr "iso2022jp-2, iso-2022-jp-2" -#: ../../library/codecs.rst:1197 +#: ../../library/codecs.rst:1231 msgid "Japanese, Korean, Simplified Chinese, Western Europe, Greek" msgstr "" -#: ../../library/codecs.rst:1200 +#: ../../library/codecs.rst:1234 msgid "iso2022_jp_2004" msgstr "iso2022_jp_2004" -#: ../../library/codecs.rst:1200 +#: ../../library/codecs.rst:1234 msgid "iso2022jp-2004, iso-2022-jp-2004" msgstr "iso2022jp-2004, iso-2022-jp-2004" -#: ../../library/codecs.rst:1203 +#: ../../library/codecs.rst:1237 msgid "iso2022_jp_3" msgstr "iso2022_jp_3" -#: ../../library/codecs.rst:1203 +#: ../../library/codecs.rst:1237 msgid "iso2022jp-3, iso-2022-jp-3" msgstr "iso2022jp-3, iso-2022-jp-3" -#: ../../library/codecs.rst:1205 +#: ../../library/codecs.rst:1239 msgid "iso2022_jp_ext" msgstr "iso2022_jp_ext" -#: ../../library/codecs.rst:1205 +#: ../../library/codecs.rst:1239 msgid "iso2022jp-ext, iso-2022-jp-ext" msgstr "iso2022jp-ext, iso-2022-jp-ext" -#: ../../library/codecs.rst:1207 +#: ../../library/codecs.rst:1241 msgid "iso2022_kr" msgstr "iso2022_kr" -#: ../../library/codecs.rst:1207 +#: ../../library/codecs.rst:1241 msgid "csiso2022kr, iso2022kr, iso-2022-kr" msgstr "csiso2022kr, iso2022kr, iso-2022-kr" -#: ../../library/codecs.rst:1210 +#: ../../library/codecs.rst:1244 msgid "latin_1" msgstr "latin_1" -#: ../../library/codecs.rst:1210 +#: ../../library/codecs.rst:1244 msgid "iso-8859-1, iso8859-1, 8859, cp819, latin, latin1, L1" msgstr "" -#: ../../library/codecs.rst:1213 +#: ../../library/codecs.rst:1247 msgid "iso8859_2" msgstr "iso8859_2" -#: ../../library/codecs.rst:1213 +#: ../../library/codecs.rst:1247 msgid "iso-8859-2, latin2, L2" msgstr "iso-8859-2, latin2, L2" -#: ../../library/codecs.rst:1215 +#: ../../library/codecs.rst:1249 msgid "iso8859_3" msgstr "iso8859_3" -#: ../../library/codecs.rst:1215 +#: ../../library/codecs.rst:1249 msgid "iso-8859-3, latin3, L3" msgstr "iso-8859-3, latin3, L3" -#: ../../library/codecs.rst:1215 +#: ../../library/codecs.rst:1249 msgid "Esperanto, Maltese" msgstr "" -#: ../../library/codecs.rst:1217 +#: ../../library/codecs.rst:1251 msgid "iso8859_4" msgstr "iso8859_4" -#: ../../library/codecs.rst:1217 +#: ../../library/codecs.rst:1251 msgid "iso-8859-4, latin4, L4" msgstr "iso-8859-4, latin4, L4" -#: ../../library/codecs.rst:1219 +#: ../../library/codecs.rst:1251 +msgid "Northern Europe" +msgstr "" + +#: ../../library/codecs.rst:1253 msgid "iso8859_5" msgstr "iso8859_5" -#: ../../library/codecs.rst:1219 +#: ../../library/codecs.rst:1253 msgid "iso-8859-5, cyrillic" msgstr "iso-8859-5, cyrillic" -#: ../../library/codecs.rst:1222 +#: ../../library/codecs.rst:1256 msgid "iso8859_6" msgstr "iso8859_6" -#: ../../library/codecs.rst:1222 +#: ../../library/codecs.rst:1256 msgid "iso-8859-6, arabic" msgstr "" -#: ../../library/codecs.rst:1224 +#: ../../library/codecs.rst:1258 msgid "iso8859_7" msgstr "iso8859_7" -#: ../../library/codecs.rst:1224 +#: ../../library/codecs.rst:1258 msgid "iso-8859-7, greek, greek8" msgstr "" -#: ../../library/codecs.rst:1226 +#: ../../library/codecs.rst:1260 msgid "iso8859_8" msgstr "iso8859_8" -#: ../../library/codecs.rst:1226 +#: ../../library/codecs.rst:1260 msgid "iso-8859-8, hebrew" msgstr "" -#: ../../library/codecs.rst:1228 +#: ../../library/codecs.rst:1262 msgid "iso8859_9" msgstr "iso8859_9" -#: ../../library/codecs.rst:1228 +#: ../../library/codecs.rst:1262 msgid "iso-8859-9, latin5, L5" msgstr "iso-8859-9, latin5, L5" -#: ../../library/codecs.rst:1230 +#: ../../library/codecs.rst:1264 msgid "iso8859_10" msgstr "iso8859_10" -#: ../../library/codecs.rst:1230 +#: ../../library/codecs.rst:1264 msgid "iso-8859-10, latin6, L6" msgstr "iso-8859-10, latin6, L6" -#: ../../library/codecs.rst:1230 +#: ../../library/codecs.rst:1264 msgid "Nordic languages" msgstr "" -#: ../../library/codecs.rst:1232 +#: ../../library/codecs.rst:1266 msgid "iso8859_11" msgstr "iso8859_11" -#: ../../library/codecs.rst:1232 +#: ../../library/codecs.rst:1266 msgid "iso-8859-11, thai" msgstr "" -#: ../../library/codecs.rst:1232 +#: ../../library/codecs.rst:1266 msgid "Thai languages" msgstr "" -#: ../../library/codecs.rst:1234 +#: ../../library/codecs.rst:1268 msgid "iso8859_13" msgstr "iso8859_13" -#: ../../library/codecs.rst:1234 +#: ../../library/codecs.rst:1268 msgid "iso-8859-13, latin7, L7" msgstr "iso-8859-13, latin7, L7" -#: ../../library/codecs.rst:1236 +#: ../../library/codecs.rst:1270 msgid "iso8859_14" msgstr "iso8859_14" -#: ../../library/codecs.rst:1236 +#: ../../library/codecs.rst:1270 msgid "iso-8859-14, latin8, L8" msgstr "iso-8859-14, latin8, L8" -#: ../../library/codecs.rst:1236 +#: ../../library/codecs.rst:1270 msgid "Celtic languages" msgstr "" -#: ../../library/codecs.rst:1238 +#: ../../library/codecs.rst:1272 msgid "iso8859_15" msgstr "iso8859_15" -#: ../../library/codecs.rst:1238 +#: ../../library/codecs.rst:1272 msgid "iso-8859-15, latin9, L9" msgstr "iso-8859-15, latin9, L9" -#: ../../library/codecs.rst:1240 +#: ../../library/codecs.rst:1274 msgid "iso8859_16" msgstr "iso8859_16" -#: ../../library/codecs.rst:1240 +#: ../../library/codecs.rst:1274 msgid "iso-8859-16, latin10, L10" msgstr "iso-8859-16, latin10, L10" -#: ../../library/codecs.rst:1240 +#: ../../library/codecs.rst:1274 msgid "South-Eastern Europe" msgstr "" -#: ../../library/codecs.rst:1242 +#: ../../library/codecs.rst:1276 msgid "johab" msgstr "" -#: ../../library/codecs.rst:1242 +#: ../../library/codecs.rst:1276 msgid "cp1361, ms1361" msgstr "cp1361, ms1361" -#: ../../library/codecs.rst:1244 +#: ../../library/codecs.rst:1278 msgid "koi8_r" msgstr "koi8_r" -#: ../../library/codecs.rst:1246 +#: ../../library/codecs.rst:1280 msgid "koi8_t" msgstr "koi8_t" -#: ../../library/codecs.rst:1246 +#: ../../library/codecs.rst:1280 msgid "Tajik" msgstr "Tajik" -#: ../../library/codecs.rst:1250 +#: ../../library/codecs.rst:1284 msgid "koi8_u" msgstr "koi8_u" -#: ../../library/codecs.rst:1252 +#: ../../library/codecs.rst:1286 msgid "kz1048" msgstr "kz1048" -#: ../../library/codecs.rst:1252 +#: ../../library/codecs.rst:1286 msgid "kz_1048, strk1048_2002, rk1048" msgstr "kz_1048, strk1048_2002, rk1048" -#: ../../library/codecs.rst:1252 ../../library/codecs.rst:1270 +#: ../../library/codecs.rst:1286 ../../library/codecs.rst:1304 msgid "Kazakh" msgstr "Cazaque" -#: ../../library/codecs.rst:1256 +#: ../../library/codecs.rst:1290 msgid "mac_cyrillic" msgstr "mac_cyrillic" -#: ../../library/codecs.rst:1256 +#: ../../library/codecs.rst:1290 msgid "maccyrillic" msgstr "maccyrillic" -#: ../../library/codecs.rst:1259 +#: ../../library/codecs.rst:1293 msgid "mac_greek" msgstr "mac_greek" -#: ../../library/codecs.rst:1259 +#: ../../library/codecs.rst:1293 msgid "macgreek" msgstr "macgreek" -#: ../../library/codecs.rst:1261 +#: ../../library/codecs.rst:1295 msgid "mac_iceland" msgstr "mac_iceland" -#: ../../library/codecs.rst:1261 +#: ../../library/codecs.rst:1295 msgid "maciceland" msgstr "maciceland" -#: ../../library/codecs.rst:1263 +#: ../../library/codecs.rst:1297 msgid "mac_latin2" msgstr "mac_latin2" -#: ../../library/codecs.rst:1263 +#: ../../library/codecs.rst:1297 msgid "maclatin2, maccentraleurope, mac_centeuro" msgstr "maclatin2, maccentraleurope, mac_centeuro" -#: ../../library/codecs.rst:1266 +#: ../../library/codecs.rst:1300 msgid "mac_roman" msgstr "mac_roman" -#: ../../library/codecs.rst:1266 +#: ../../library/codecs.rst:1300 msgid "macroman, macintosh" msgstr "" -#: ../../library/codecs.rst:1268 +#: ../../library/codecs.rst:1302 msgid "mac_turkish" msgstr "mac_turkish" -#: ../../library/codecs.rst:1268 +#: ../../library/codecs.rst:1302 msgid "macturkish" msgstr "macturkish" -#: ../../library/codecs.rst:1270 +#: ../../library/codecs.rst:1304 msgid "ptcp154" msgstr "ptcp154" -#: ../../library/codecs.rst:1270 +#: ../../library/codecs.rst:1304 msgid "csptcp154, pt154, cp154, cyrillic-asian" msgstr "" -#: ../../library/codecs.rst:1273 +#: ../../library/codecs.rst:1307 msgid "shift_jis" msgstr "shift_jis" -#: ../../library/codecs.rst:1273 +#: ../../library/codecs.rst:1307 msgid "csshiftjis, shiftjis, sjis, s_jis" msgstr "" -#: ../../library/codecs.rst:1276 +#: ../../library/codecs.rst:1310 msgid "shift_jis_2004" msgstr "shift_jis_2004" -#: ../../library/codecs.rst:1276 +#: ../../library/codecs.rst:1310 msgid "shiftjis2004, sjis_2004, sjis2004" msgstr "shiftjis2004, sjis_2004, sjis2004" -#: ../../library/codecs.rst:1279 +#: ../../library/codecs.rst:1313 msgid "shift_jisx0213" msgstr "shift_jisx0213" -#: ../../library/codecs.rst:1279 +#: ../../library/codecs.rst:1313 msgid "shiftjisx0213, sjisx0213, s_jisx0213" msgstr "shiftjisx0213, sjisx0213, s_jisx0213" -#: ../../library/codecs.rst:1282 +#: ../../library/codecs.rst:1316 msgid "utf_32" msgstr "utf_32" -#: ../../library/codecs.rst:1282 +#: ../../library/codecs.rst:1316 msgid "U32, utf32" msgstr "U32, utf32" -#: ../../library/codecs.rst:1282 ../../library/codecs.rst:1284 -#: ../../library/codecs.rst:1286 ../../library/codecs.rst:1288 -#: ../../library/codecs.rst:1290 ../../library/codecs.rst:1292 -#: ../../library/codecs.rst:1294 ../../library/codecs.rst:1296 -#: ../../library/codecs.rst:1298 +#: ../../library/codecs.rst:1316 ../../library/codecs.rst:1318 +#: ../../library/codecs.rst:1320 ../../library/codecs.rst:1322 +#: ../../library/codecs.rst:1324 ../../library/codecs.rst:1326 +#: ../../library/codecs.rst:1328 ../../library/codecs.rst:1330 +#: ../../library/codecs.rst:1332 msgid "all languages" msgstr "todas linguagens" -#: ../../library/codecs.rst:1284 +#: ../../library/codecs.rst:1318 msgid "utf_32_be" msgstr "utf_32_be" -#: ../../library/codecs.rst:1284 +#: ../../library/codecs.rst:1318 msgid "UTF-32BE" msgstr "UTF-32BE" -#: ../../library/codecs.rst:1286 +#: ../../library/codecs.rst:1320 msgid "utf_32_le" msgstr "utf_32_le" -#: ../../library/codecs.rst:1286 +#: ../../library/codecs.rst:1320 msgid "UTF-32LE" msgstr "UTF-32LE" -#: ../../library/codecs.rst:1288 +#: ../../library/codecs.rst:1322 msgid "utf_16" msgstr "utf_16" -#: ../../library/codecs.rst:1288 +#: ../../library/codecs.rst:1322 msgid "U16, utf16" msgstr "U16, utf16" -#: ../../library/codecs.rst:1290 +#: ../../library/codecs.rst:1324 msgid "utf_16_be" msgstr "utf_16_be" -#: ../../library/codecs.rst:1290 +#: ../../library/codecs.rst:1324 msgid "UTF-16BE" msgstr "UTF-16BE" -#: ../../library/codecs.rst:1292 +#: ../../library/codecs.rst:1326 msgid "utf_16_le" msgstr "utf_16_le" -#: ../../library/codecs.rst:1292 +#: ../../library/codecs.rst:1326 msgid "UTF-16LE" msgstr "UTF-16LE" -#: ../../library/codecs.rst:1294 +#: ../../library/codecs.rst:1328 msgid "utf_7" msgstr "utf_7" -#: ../../library/codecs.rst:1294 +#: ../../library/codecs.rst:1328 msgid "U7, unicode-1-1-utf-7" msgstr "U7, unicode-1-1-utf-7" -#: ../../library/codecs.rst:1296 +#: ../../library/codecs.rst:1330 msgid "utf_8" msgstr "utf_8" -#: ../../library/codecs.rst:1296 +#: ../../library/codecs.rst:1330 msgid "U8, UTF, utf8, cp65001" msgstr "" -#: ../../library/codecs.rst:1298 +#: ../../library/codecs.rst:1332 msgid "utf_8_sig" msgstr "utf_8_sig" -#: ../../library/codecs.rst:1301 +#: ../../library/codecs.rst:1335 msgid "" "The utf-16\\* and utf-32\\* encoders no longer allow surrogate code points " "(``U+D800``--``U+DFFF``) to be encoded. The utf-32\\* decoders no longer " "decode byte sequences that correspond to surrogate code points." msgstr "" -#: ../../library/codecs.rst:1307 +#: ../../library/codecs.rst:1341 msgid "``cp65001`` is now an alias to ``utf_8``." msgstr "" -#: ../../library/codecs.rst:1312 +#: ../../library/codecs.rst:1346 msgid "Python Specific Encodings" msgstr "" -#: ../../library/codecs.rst:1314 +#: ../../library/codecs.rst:1348 msgid "" "A number of predefined codecs are specific to Python, so their codec names " "have no meaning outside Python. These are listed in the tables below based " @@ -2318,268 +2356,369 @@ msgid "" "asymmetric codecs, the stated meaning describes the encoding direction." msgstr "" -#: ../../library/codecs.rst:1322 +#: ../../library/codecs.rst:1356 msgid "Text Encodings" msgstr "" -#: ../../library/codecs.rst:1324 +#: ../../library/codecs.rst:1358 msgid "" "The following codecs provide :class:`str` to :class:`bytes` encoding and :" "term:`bytes-like object` to :class:`str` decoding, similar to the Unicode " "text encodings." msgstr "" -#: ../../library/codecs.rst:1333 +#: ../../library/codecs.rst:1367 msgid "idna" msgstr "idna" -#: ../../library/codecs.rst:1333 +#: ../../library/codecs.rst:1367 msgid "" "Implement :rfc:`3490`, see also :mod:`encodings.idna`. Only " "``errors='strict'`` is supported." msgstr "" -#: ../../library/codecs.rst:1339 +#: ../../library/codecs.rst:1373 msgid "mbcs" msgstr "mbcs" -#: ../../library/codecs.rst:1339 +#: ../../library/codecs.rst:1373 msgid "ansi, dbcs" msgstr "ansi, dbcs" -#: ../../library/codecs.rst:1339 +#: ../../library/codecs.rst:1373 msgid "" "Windows only: Encode the operand according to the ANSI codepage (CP_ACP)." msgstr "" -#: ../../library/codecs.rst:1343 +#: ../../library/codecs.rst:1377 msgid "oem" msgstr "oem" -#: ../../library/codecs.rst:1343 +#: ../../library/codecs.rst:1377 msgid "" "Windows only: Encode the operand according to the OEM codepage (CP_OEMCP)." msgstr "" -#: ../../library/codecs.rst:1349 +#: ../../library/codecs.rst:1383 msgid "palmos" msgstr "" -#: ../../library/codecs.rst:1349 +#: ../../library/codecs.rst:1383 msgid "Encoding of PalmOS 3.5." msgstr "" -#: ../../library/codecs.rst:1351 +#: ../../library/codecs.rst:1385 msgid "punycode" msgstr "punycode" -#: ../../library/codecs.rst:1351 +#: ../../library/codecs.rst:1385 msgid "Implement :rfc:`3492`. Stateful codecs are not supported." msgstr "" -#: ../../library/codecs.rst:1355 +#: ../../library/codecs.rst:1389 msgid "raw_unicode_escape" msgstr "raw_unicode_escape" -#: ../../library/codecs.rst:1355 +#: ../../library/codecs.rst:1389 msgid "" "Latin-1 encoding with :samp:`\\\\u{XXXX}` and :samp:`\\\\U{XXXXXXXX}` for " "other code points. Existing backslashes are not escaped in any way. It is " "used in the Python pickle protocol." msgstr "" -#: ../../library/codecs.rst:1365 +#: ../../library/codecs.rst:1399 msgid "undefined" msgstr "" -#: ../../library/codecs.rst:1365 +#: ../../library/codecs.rst:1399 +msgid "This Codec should only be used for testing purposes." +msgstr "" + +#: ../../library/codecs.rst:1403 msgid "" "Raise an exception for all conversions, even empty strings. The error " "handler is ignored." msgstr "" -#: ../../library/codecs.rst:1370 +#: ../../library/codecs.rst:1408 msgid "unicode_escape" msgstr "unicode_escape" -#: ../../library/codecs.rst:1370 +#: ../../library/codecs.rst:1408 msgid "" "Encoding suitable as the contents of a Unicode literal in ASCII-encoded " "Python source code, except that quotes are not escaped. Decode from Latin-1 " "source code. Beware that Python source code actually uses UTF-8 by default." msgstr "" -#: ../../library/codecs.rst:1382 +#: ../../library/codecs.rst:1420 msgid "\"unicode_internal\" codec is removed." msgstr "" -#: ../../library/codecs.rst:1389 +#: ../../library/codecs.rst:1427 msgid "Binary Transforms" msgstr "" -#: ../../library/codecs.rst:1391 +#: ../../library/codecs.rst:1429 msgid "" "The following codecs provide binary transforms: :term:`bytes-like object` " "to :class:`bytes` mappings. They are not supported by :meth:`bytes.decode` " "(which only produces :class:`str` output)." msgstr "" -#: ../../library/codecs.rst:1399 +#: ../../library/codecs.rst:1437 msgid "Encoder / decoder" msgstr "" -#: ../../library/codecs.rst:1401 +#: ../../library/codecs.rst:1439 msgid "base64_codec [#b64]_" msgstr "base64_codec [#b64]_" -#: ../../library/codecs.rst:1401 +#: ../../library/codecs.rst:1439 msgid "base64, base_64" msgstr "base64, base_64" -#: ../../library/codecs.rst:1401 +#: ../../library/codecs.rst:1439 msgid "" "Convert the operand to multiline MIME base64 (the result always includes a " "trailing ``'\\n'``)." msgstr "" -#: ../../library/codecs.rst:1406 +#: ../../library/codecs.rst:1444 msgid "" "accepts any :term:`bytes-like object` as input for encoding and decoding" msgstr "" -#: ../../library/codecs.rst:1401 +#: ../../library/codecs.rst:1439 msgid ":meth:`base64.encodebytes` / :meth:`base64.decodebytes`" msgstr ":meth:`base64.encodebytes` / :meth:`base64.decodebytes`" -#: ../../library/codecs.rst:1412 +#: ../../library/codecs.rst:1450 msgid "bz2_codec" msgstr "bz2_codec" -#: ../../library/codecs.rst:1412 +#: ../../library/codecs.rst:1450 msgid "bz2" msgstr "bz2" -#: ../../library/codecs.rst:1412 +#: ../../library/codecs.rst:1450 msgid "Compress the operand using bz2." msgstr "" -#: ../../library/codecs.rst:1412 +#: ../../library/codecs.rst:1450 msgid ":meth:`bz2.compress` / :meth:`bz2.decompress`" msgstr ":meth:`bz2.compress` / :meth:`bz2.decompress`" -#: ../../library/codecs.rst:1415 +#: ../../library/codecs.rst:1453 msgid "hex_codec" msgstr "hex_codec" -#: ../../library/codecs.rst:1415 +#: ../../library/codecs.rst:1453 msgid "hex" msgstr "hex" -#: ../../library/codecs.rst:1415 +#: ../../library/codecs.rst:1453 msgid "" "Convert the operand to hexadecimal representation, with two digits per byte." msgstr "" -#: ../../library/codecs.rst:1415 +#: ../../library/codecs.rst:1453 msgid ":meth:`binascii.b2a_hex` / :meth:`binascii.a2b_hex`" msgstr ":meth:`binascii.b2a_hex` / :meth:`binascii.a2b_hex`" -#: ../../library/codecs.rst:1420 +#: ../../library/codecs.rst:1458 msgid "quopri_codec" msgstr "quopri_codec" -#: ../../library/codecs.rst:1420 +#: ../../library/codecs.rst:1458 msgid "quopri, quotedprintable, quoted_printable" msgstr "" -#: ../../library/codecs.rst:1420 +#: ../../library/codecs.rst:1458 msgid "Convert the operand to MIME quoted printable." msgstr "" -#: ../../library/codecs.rst:1420 +#: ../../library/codecs.rst:1458 msgid ":meth:`quopri.encode` with ``quotetabs=True`` / :meth:`quopri.decode`" msgstr ":meth:`quopri.encode` with ``quotetabs=True`` / :meth:`quopri.decode`" -#: ../../library/codecs.rst:1424 +#: ../../library/codecs.rst:1462 msgid "uu_codec" msgstr "uu_codec" -#: ../../library/codecs.rst:1424 +#: ../../library/codecs.rst:1462 msgid "uu" msgstr "uu" -#: ../../library/codecs.rst:1424 +#: ../../library/codecs.rst:1462 msgid "Convert the operand using uuencode." msgstr "" -#: ../../library/codecs.rst:1427 +#: ../../library/codecs.rst:1465 msgid "zlib_codec" msgstr "zlib_codec" -#: ../../library/codecs.rst:1427 +#: ../../library/codecs.rst:1465 msgid "zip, zlib" msgstr "" -#: ../../library/codecs.rst:1427 +#: ../../library/codecs.rst:1465 msgid "Compress the operand using gzip." msgstr "" -#: ../../library/codecs.rst:1427 +#: ../../library/codecs.rst:1465 msgid ":meth:`zlib.compress` / :meth:`zlib.decompress`" msgstr ":meth:`zlib.compress` / :meth:`zlib.decompress`" -#: ../../library/codecs.rst:1431 +#: ../../library/codecs.rst:1469 msgid "" "In addition to :term:`bytes-like objects `, " "``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for " "decoding" msgstr "" -#: ../../library/codecs.rst:1435 +#: ../../library/codecs.rst:1473 msgid "Restoration of the binary transforms." msgstr "" -#: ../../library/codecs.rst:1438 +#: ../../library/codecs.rst:1476 msgid "Restoration of the aliases for the binary transforms." msgstr "" -#: ../../library/codecs.rst:1445 +#: ../../library/codecs.rst:1483 +msgid "Standalone Codec Functions" +msgstr "" + +#: ../../library/codecs.rst:1485 +msgid "" +"The following functions provide encoding and decoding functionality similar " +"to codecs, but are not available as named codecs through :func:`codecs." +"encode` or :func:`codecs.decode`. They are used internally (for example, by :" +"mod:`pickle`) and behave similarly to the ``string_escape`` codec that was " +"removed in Python 3." +msgstr "" + +#: ../../library/codecs.rst:1492 +msgid "" +"Encode *input* using escape sequences. Similar to how :func:`repr` on bytes " +"produces escaped byte values." +msgstr "" + +#: ../../library/codecs.rst:1495 +msgid "*input* must be a :class:`bytes` object." +msgstr "" + +#: ../../library/codecs.rst:1497 ../../library/codecs.rst:1506 +msgid "" +"Returns a tuple ``(output, length)`` where *output* is a :class:`bytes` " +"object and *length* is the number of bytes consumed." +msgstr "" + +#: ../../library/codecs.rst:1502 +msgid "Decode *input* from escape sequences back to the original bytes." +msgstr "" + +#: ../../library/codecs.rst:1504 +msgid "*input* must be a :term:`bytes-like object`." +msgstr "" + +#: ../../library/codecs.rst:1513 msgid "Text Transforms" msgstr "" -#: ../../library/codecs.rst:1447 +#: ../../library/codecs.rst:1515 msgid "" "The following codec provides a text transform: a :class:`str` to :class:" "`str` mapping. It is not supported by :meth:`str.encode` (which only " "produces :class:`bytes` output)." msgstr "" -#: ../../library/codecs.rst:1456 +#: ../../library/codecs.rst:1524 msgid "rot_13" msgstr "rot_13" -#: ../../library/codecs.rst:1456 +#: ../../library/codecs.rst:1524 msgid "rot13" msgstr "rot13" -#: ../../library/codecs.rst:1456 +#: ../../library/codecs.rst:1524 msgid "Return the Caesar-cypher encryption of the operand." msgstr "" -#: ../../library/codecs.rst:1461 +#: ../../library/codecs.rst:1529 msgid "Restoration of the ``rot_13`` text transform." msgstr "" -#: ../../library/codecs.rst:1464 +#: ../../library/codecs.rst:1532 msgid "Restoration of the ``rot13`` alias." msgstr "" -#: ../../library/codecs.rst:1469 +#: ../../library/codecs.rst:1537 +msgid ":mod:`encodings` --- Encodings package" +msgstr "" + +#: ../../library/codecs.rst:1542 +msgid "This module implements the following functions:" +msgstr "" + +#: ../../library/codecs.rst:1546 +msgid "Normalize encoding name *encoding*." +msgstr "" + +#: ../../library/codecs.rst:1548 +msgid "" +"Normalization works as follows: all non-alphanumeric characters except the " +"dot used for Python package names are collapsed and replaced with a single " +"underscore, leading and trailing underscores are removed. For example, ``' " +"-;#'`` becomes ``'_'``." +msgstr "" + +#: ../../library/codecs.rst:1553 +msgid "Note that *encoding* should be ASCII only." +msgstr "" + +#: ../../library/codecs.rst:1557 +msgid "" +"The following function should not be used directly, except for testing " +"purposes; :func:`codecs.lookup` should be used instead." +msgstr "" + +#: ../../library/codecs.rst:1563 +msgid "" +"Search for the codec module corresponding to the given encoding name " +"*encoding*." +msgstr "" + +#: ../../library/codecs.rst:1566 +msgid "" +"This function first normalizes the *encoding* using :func:" +"`normalize_encoding`, then looks for a corresponding alias. It attempts to " +"import a codec module from the encodings package using either the alias or " +"the normalized name. If the module is found and defines a valid " +"``getregentry()`` function that returns a :class:`codecs.CodecInfo` object, " +"the codec is cached and returned." +msgstr "" + +#: ../../library/codecs.rst:1573 +msgid "" +"If the codec module defines a ``getaliases()`` function any returned aliases " +"are registered for future use." +msgstr "" + +#: ../../library/codecs.rst:1577 +msgid "This module implements the following exception:" +msgstr "" + +#: ../../library/codecs.rst:1581 +msgid "Raised when a codec is invalid or incompatible." +msgstr "" + +#: ../../library/codecs.rst:1585 msgid "" ":mod:`encodings.idna` --- Internationalized Domain Names in Applications" msgstr "" -#: ../../library/codecs.rst:1475 +#: ../../library/codecs.rst:1591 msgid "" "This module implements :rfc:`3490` (Internationalized Domain Names in " "Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for " @@ -2587,13 +2726,13 @@ msgid "" "encoding and :mod:`stringprep`." msgstr "" -#: ../../library/codecs.rst:1480 +#: ../../library/codecs.rst:1596 msgid "" "If you need the IDNA 2008 standard from :rfc:`5891` and :rfc:`5895`, use the " "third-party :pypi:`idna` module." msgstr "" -#: ../../library/codecs.rst:1483 +#: ../../library/codecs.rst:1599 msgid "" "These RFCs together define a protocol to support non-ASCII characters in " "domain names. A domain name containing non-ASCII characters (such as ``www." @@ -2607,7 +2746,7 @@ msgid "" "presenting them to the user." msgstr "" -#: ../../library/codecs.rst:1494 +#: ../../library/codecs.rst:1610 msgid "" "Python supports this conversion in several ways: the ``idna`` codec " "performs conversion between Unicode and ACE, separating an input string into " @@ -2624,14 +2763,14 @@ msgid "" "sends that field at all)." msgstr "" -#: ../../library/codecs.rst:1507 +#: ../../library/codecs.rst:1623 msgid "" "When receiving host names from the wire (such as in reverse name lookup), no " "automatic conversion to Unicode is performed: applications wishing to " "present such host names to the user should decode them to Unicode." msgstr "" -#: ../../library/codecs.rst:1511 +#: ../../library/codecs.rst:1627 msgid "" "The module :mod:`encodings.idna` also implements the nameprep procedure, " "which performs certain normalizations on host names, to achieve case-" @@ -2639,49 +2778,49 @@ msgid "" "characters. The nameprep functions can be used directly if desired." msgstr "" -#: ../../library/codecs.rst:1519 +#: ../../library/codecs.rst:1635 msgid "" "Return the nameprepped version of *label*. The implementation currently " "assumes query strings, so ``AllowUnassigned`` is true." msgstr "" -#: ../../library/codecs.rst:1525 +#: ../../library/codecs.rst:1641 msgid "" "Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` " "is assumed to be false." msgstr "" -#: ../../library/codecs.rst:1531 +#: ../../library/codecs.rst:1647 msgid "Convert a label to Unicode, as specified in :rfc:`3490`." msgstr "" -#: ../../library/codecs.rst:1535 +#: ../../library/codecs.rst:1651 msgid ":mod:`encodings.mbcs` --- Windows ANSI codepage" msgstr "" -#: ../../library/codecs.rst:1540 +#: ../../library/codecs.rst:1656 msgid "This module implements the ANSI codepage (CP_ACP)." msgstr "" -#: ../../library/codecs.rst:1542 -msgid ":ref:`Availability `: Windows." -msgstr ":ref:`Disponibilidade `: Windows." +#: ../../library/codecs.rst:1658 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/codecs.rst:1544 +#: ../../library/codecs.rst:1660 msgid "" "Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used " "to encode, and ``'ignore'`` to decode." msgstr "" -#: ../../library/codecs.rst:1548 +#: ../../library/codecs.rst:1664 msgid "Support any error handler." msgstr "" -#: ../../library/codecs.rst:1553 +#: ../../library/codecs.rst:1669 msgid ":mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature" msgstr "" -#: ../../library/codecs.rst:1559 +#: ../../library/codecs.rst:1675 msgid "" "This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 " "encoded BOM will be prepended to the UTF-8 encoded bytes. For the stateful " @@ -2710,67 +2849,67 @@ msgstr "" msgid "stackable" msgstr "" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "strict" msgstr "" -#: ../../library/codecs.rst:312 ../../library/codecs.rst:364 -#: ../../library/codecs.rst:387 +#: ../../library/codecs.rst:334 ../../library/codecs.rst:386 +#: ../../library/codecs.rst:409 msgid "error handler's name" msgstr "" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "ignore" msgstr "" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "replace" msgstr "" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "backslashreplace" msgstr "backslashreplace" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "surrogateescape" msgstr "surrogateescape" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "? (question mark)" msgstr "? (interrogação)" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "replacement character" msgstr "" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "\\ (backslash)" msgstr "\\ (contrabarra)" -#: ../../library/codecs.rst:312 ../../library/codecs.rst:364 +#: ../../library/codecs.rst:334 ../../library/codecs.rst:386 msgid "escape sequence" msgstr "sequência de escape" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "\\x" msgstr "\\x" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "\\u" msgstr "\\u" -#: ../../library/codecs.rst:312 +#: ../../library/codecs.rst:334 msgid "\\U" msgstr "\\U" -#: ../../library/codecs.rst:364 +#: ../../library/codecs.rst:386 msgid "xmlcharrefreplace" msgstr "xmlcharrefreplace" -#: ../../library/codecs.rst:364 +#: ../../library/codecs.rst:386 msgid "namereplace" msgstr "namereplace" -#: ../../library/codecs.rst:387 +#: ../../library/codecs.rst:409 msgid "surrogatepass" msgstr "surrogatepass" diff --git a/library/codeop.po b/library/codeop.po index ef5619620..ede80ae5d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..53a4f170f 100644 --- a/library/collections.abc.po +++ b/library/collections.abc.po @@ -1,34 +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: -# Marco Rougeth , 2021 -# Vinícius Muniz de Melo , 2021 -# Vitor Buxbaum Orlandi, 2023 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# 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-11-05 15:17+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +43,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 +153,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: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:99 +#: ../../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 +198,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 "Métodos herdados 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 +449,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 +553,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 +567,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 +613,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,70 +632,144 @@ 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: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:262 +#: ../../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 " -"calls to the underlying :meth:`~object.__getitem__` method. Consequently, " -"if :meth:`~object.__getitem__` is implemented with constant access speed, " -"the mixin methods will have linear performance; however, if the underlying " -"method is linear (as it would be with a linked list), the mixins will have " -"quadratic performance and will likely need to be overridden." +"__iter__`, :meth:`~object.__reversed__`, and :meth:`~sequence.index` make " +"repeated calls to the underlying :meth:`~object.__getitem__` method. " +"Consequently, if :meth:`~object.__getitem__` is implemented with constant " +"access speed, the mixin methods will have linear performance; however, if " +"the underlying 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 métodos mixin, como :meth:`~container." +"__iter__`, :meth:`~object.__reversed__` e :meth:`~sequence.index`, fazem " +"chamadas repetidas ao 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ão " +"ser substituídos." + +#: ../../library/collections.abc.rst:282 +msgid "Return first index of *value*." +msgstr "Retorna o primeiro índice de *valor*." + +#: ../../library/collections.abc.rst:284 +msgid "Raises :exc:`ValueError` if the value is not present." +msgstr "Levanta :exc:`ValueError` se o valor não estiver presente." + +#: ../../library/collections.abc.rst:286 +msgid "" +"Supporting the *start* and *stop* arguments is optional, but recommended." +msgstr "Suporte aos argumentos *start* e *stop* é opcional, mas recomendado." + +#: ../../library/collections.abc.rst:288 +msgid "" +"The :meth:`~sequence.index` method gained support for the *stop* and *start* " +"arguments." msgstr "" +"O método :meth:`~sequence.index` ganhou suporte para os argumentos *stop* e " +"*start*." + +#: ../../library/collections.abc.rst:292 +msgid "The :class:`ByteString` ABC has been deprecated." +msgstr "A ABC :class:`ByteString` foi descontinuada." -#: ../../library/collections.abc.rst:273 -msgid "The index() method added support for *stop* and *start* arguments." +#: ../../library/collections.abc.rst:295 +msgid "" +"Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj`` " +"implements the :ref:`buffer protocol ` at runtime. For use in " +"type annotations, either use :class:`Buffer` or a union that explicitly " +"specifies the types your code supports (e.g., ``bytes | bytearray | " +"memoryview``)." msgstr "" -"O método index() adicionou suporte para os argumentos *stop* e *start*." +"Use ``isinstance(obj, collections.abc.Buffer)`` para testar se ``obj`` " +"implementa o :ref:`protocolo de buffer ` em tempo de " +"execução. Para uso em anotações de tipo, use :class:`Buffer` ou uma união " +"que especifique explicitamente os tipos suportados pelo seu código (por " +"exemplo, ``bytes | bytearray | memoryview``)." -#: ../../library/collections.abc.rst:277 +#: ../../library/collections.abc.rst:301 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`." +":class:`!ByteString` was originally intended to be an abstract class that " +"would serve as a supertype of both :class:`bytes` and :class:`bytearray`. " +"However, since the ABC never had any methods, knowing that an object was an " +"instance of :class:`!ByteString` never actually told you anything useful " +"about the object. Other common buffer types such as :class:`memoryview` were " +"also never understood as subtypes of :class:`!ByteString` (either at runtime " +"or by static type checkers)." msgstr "" +":class:`!ByteString` foi originalmente concebido para ser uma classe " +"abstrata que serviria como um supertipo de :class:`bytes` e :class:" +"`bytearray`. No entanto, como o ABC nunca teve métodos, saber que um objeto " +"era uma instância de :class:`!ByteString` nunca lhe dizia nada de útil sobre " +"o objeto. Outros tipos comuns de buffer, como :class:`memoryview`, também " +"nunca foram entendidos como subtipos de :class:`!ByteString` (seja em tempo " +"de execução ou por verificadores de tipo estáticos)." -#: ../../library/collections.abc.rst:286 +#: ../../library/collections.abc.rst:309 +msgid "See :pep:`PEP 688 <688#current-options>` for more details." +msgstr " Consulte :pep:`PEP <688#current-options>` para mais detalhes." + +#: ../../library/collections.abc.rst:314 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:319 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:326 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:330 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:334 msgid "" ":term:`Coroutine ` objects and instances of the :class:" "`~collections.abc.Coroutine` ABC are all instances of this ABC." @@ -560,16 +777,21 @@ 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:338 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " -"decorated with :func:`@types.coroutine `) are *awaitables*, " -"even though they do not have an :meth:`~object.__await__` method. Using " -"``isinstance(gencoro, Awaitable)`` for them will return ``False``. Use :func:" -"`inspect.isawaitable` to detect them." +"decorated with :deco:`types.coroutine`) are *awaitables*, even though they " +"do not have an :meth:`~object.__await__` method. Using ``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 :deco:`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:348 msgid "" "ABC for :term:`coroutine` compatible classes. These implement the following " "methods, defined in :ref:`coroutine-objects`: :meth:`~coroutine.send`, :meth:" @@ -577,23 +799,45 @@ 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:356 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " -"decorated with :func:`@types.coroutine `) are *awaitables*, " -"even though they do not have an :meth:`~object.__await__` method. Using " -"``isinstance(gencoro, Coroutine)`` for them will return ``False``. Use :func:" -"`inspect.isawaitable` to detect them." +"decorated with :deco:`types.coroutine`) are *awaitables*, even though they " +"do not have an :meth:`~object.__await__` method. Using ``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 :deco:`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:362 +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:371 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:378 msgid "" "ABC for classes that provide ``__aiter__`` and ``__anext__`` methods. See " "also the definition of :term:`asynchronous iterator`." @@ -601,29 +845,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:385 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:388 +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:395 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:401 msgid "Examples and Recipes" msgstr "Exemplos e receitas" -#: ../../library/collections.abc.rst:367 +#: ../../library/collections.abc.rst:403 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:406 +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:410 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 +900,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:403 +#: ../../library/collections.abc.rst:417 +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:439 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:442 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 +971,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:453 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:459 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 +1000,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:467 msgid "" "`OrderedSet recipe `_ for an " "example built on :class:`MutableSet`." @@ -674,7 +1015,7 @@ msgstr "" "`OrderedSet receita `_ para um " "exemplo baseado em :class:`MutableSet`." -#: ../../library/collections.abc.rst:434 +#: ../../library/collections.abc.rst:470 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..0e0ae2286 100644 --- a/library/collections.po +++ b/library/collections.po @@ -1,34 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +207,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 +263,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 +283,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 +360,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 +378,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 +418,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 +467,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 +534,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 +724,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 +766,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 +924,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 +1136,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 +1266,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 +1286,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 +1365,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 +1419,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 +1470,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 +1494,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 "" @@ -1163,17 +1596,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 similares 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 +1618,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 +1631,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 +1643,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 +1659,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 +1675,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 +1683,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 +1695,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 +1749,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 +1793,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 +1818,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 +1845,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 +1853,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 +1886,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 +1894,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 +1938,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 +1946,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 +1956,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 +1996,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 +2006,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 +2014,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 +2028,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 +2048,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 +2056,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 +2073,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 +2085,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 +2095,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 +2105,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 +2120,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 +2139,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 +2149,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 +2167,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 +2177,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 +2192,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 +2204,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 +2215,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 +2241,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 +2271,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 +2297,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 +2321,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 +2460,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 +2474,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 +2482,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 +2505,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 +2516,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 +2530,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 +2538,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 +2546,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 +2562,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 +2574,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 +2591,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 +2605,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 +2613,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 +2621,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..c730951bb 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..127d157c8 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -119,16 +118,32 @@ msgstr "" "casos em que o arquivo de origem não exista no momento em que o arquivo de " "bytecode for executado." -#: ../../library/compileall.rst:61 +#: ../../library/compileall.rst:60 msgid "" -"Remove (``-s``) or append (``-p``) the given prefix of paths recorded in the " -"``.pyc`` files. Cannot be combined with ``-d``." +"Remove the given prefix from paths recorded in the ``.pyc`` files. Paths are " +"made relative to the prefix." msgstr "" -"Remove (``-s``) ou acrescenta (``-p``) o prefixo especificado dos caminhos " -"gravados nos arquivos ``.pyc``. Não pode ser combinado com ``-d``." +"Remove o prefixo especificado dos caminhos gravados nos arquivos ``.pyc``. " +"Caminhos são tornados relativos ao prefixo." + +#: ../../library/compileall.rst:63 +msgid "This option can be used with ``-p`` but not with ``-d``." +msgstr "Esta opção pode ser usada com ``-p``, mas não com ``-d``." #: ../../library/compileall.rst:67 msgid "" +"Prepend the given prefix to paths recorded in the ``.pyc`` files. Use ``-p /" +"`` to make the paths absolute." +msgstr "" +"Adiciona o prefixo fornecido aos caminhos registrados nos arquivos ``.pyc``. " +"Use ``-p /`` para tornar os caminhos absolutos." + +#: ../../library/compileall.rst:70 +msgid "This option can be used with ``-s`` but not with ``-d``." +msgstr "Esta opção pode ser usada com ``-s``, mas não com ``-d``." + +#: ../../library/compileall.rst:74 +msgid "" "regex is used to search the full path to each file considered for " "compilation, and if the regex produces a match, the file is skipped." msgstr "" @@ -136,7 +151,7 @@ msgstr "" "cada arquivo considerado para compilação e, se a ``regex`` produzir uma " "correspondência, o arquivo será ignorado." -#: ../../library/compileall.rst:72 +#: ../../library/compileall.rst:79 msgid "" "Read the file ``list`` and add each line that it contains to the list of " "files and directories to compile. If ``list`` is ``-``, read lines from " @@ -146,7 +161,7 @@ msgstr "" "arquivos e diretórios a serem compilados. Se ``list`` for ``-``, lê as " "linhas do ``stdin``." -#: ../../library/compileall.rst:78 +#: ../../library/compileall.rst:85 msgid "" "Write the byte-code files to their legacy locations and names, which may " "overwrite byte-code files created by another version of Python. The default " @@ -158,7 +173,7 @@ msgstr "" "padrão é gravar arquivos em seus locais e nomes do :pep:`3147`, o que " "permite que arquivos de bytecode de várias versões do Python coexistam." -#: ../../library/compileall.rst:85 +#: ../../library/compileall.rst:92 msgid "" "Control the maximum recursion level for subdirectories. If this is given, " "then ``-l`` option will not be taken into account. :program:`python -m " @@ -170,15 +185,15 @@ msgstr "" " -r 0` é equivalente a :program:`python -m compileall " "-l`." -#: ../../library/compileall.rst:92 +#: ../../library/compileall.rst:99 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 +#: ../../library/compileall.rst:105 msgid "" "Control how the generated byte-code files are invalidated at runtime. The " "``timestamp`` value, means that ``.pyc`` files with the source timestamp and " @@ -202,7 +217,7 @@ msgstr "" "estiver configurada e ``selected-hash`` se a variável de ambiente " "``SOURCE_DATE_EPOCH`` estiver configurada." -#: ../../library/compileall.rst:111 +#: ../../library/compileall.rst:118 msgid "" "Compile with the given optimization level. May be used multiple times to " "compile for multiple levels at a time (for example, ``compileall -o 1 -o " @@ -212,12 +227,12 @@ msgstr "" "para compilar para vários níveis por vez (por exemplo, ``compileall -o 1 -o " "2``)." -#: ../../library/compileall.rst:117 +#: ../../library/compileall.rst:124 msgid "Ignore symlinks pointing outside the given directory." msgstr "" "Ignora links simbólicos que apontam para fora do diretório especificado." -#: ../../library/compileall.rst:121 +#: ../../library/compileall.rst:128 msgid "" "If two ``.pyc`` files with different optimization level have the same " "content, use hard links to consolidate duplicate files." @@ -225,11 +240,11 @@ msgstr "" "Se dois arquivos ``.pyc`` com nível de otimização diferente tiverem o mesmo " "conteúdo, usa links físicos para consolidar arquivos duplicados." -#: ../../library/compileall.rst:124 +#: ../../library/compileall.rst:131 msgid "Added the ``-i``, ``-b`` and ``-h`` options." msgstr "Adicionadas as opções ``-i``, ``-b`` e ``-h``." -#: ../../library/compileall.rst:127 +#: ../../library/compileall.rst:134 msgid "" "Added the ``-j``, ``-r``, and ``-qq`` options. ``-q`` option was changed " "to a multilevel value. ``-b`` will always produce a byte-code file ending " @@ -239,11 +254,11 @@ msgstr "" "para um valor multinível. ``-b`` sempre produzirá um arquivo de bytecodes " "que termina em ``.pyc``, nunca em ``.pyo``." -#: ../../library/compileall.rst:132 +#: ../../library/compileall.rst:139 msgid "Added the ``--invalidation-mode`` option." msgstr "Adicionada a opção ``--invalidation-mode``." -#: ../../library/compileall.rst:135 +#: ../../library/compileall.rst:142 msgid "" "Added the ``-s``, ``-p``, ``-e`` and ``--hardlink-dupes`` options. Raised " "the default recursion limit from 10 to :py:func:`sys.getrecursionlimit()`. " @@ -254,7 +269,7 @@ msgstr "" "getrecursionlimit()`. Adicionada a possibilidade de especificar a opção ``-" "o`` várias vezes." -#: ../../library/compileall.rst:142 +#: ../../library/compileall.rst:149 msgid "" "There is no command-line option to control the optimization level used by " "the :func:`compile` function, because the Python interpreter itself already " @@ -264,7 +279,7 @@ msgstr "" "pela função :func:`compile` porque o próprio interpretador Python já fornece " "a opção: :program:`python -O -m compileall`." -#: ../../library/compileall.rst:146 +#: ../../library/compileall.rst:153 msgid "" "Similarly, the :func:`compile` function respects the :data:`sys." "pycache_prefix` setting. The generated bytecode cache will only be useful " @@ -276,11 +291,11 @@ msgstr "" "`compile` for executado com o mesmo :data:`sys.pycache_prefix` (se houver) " "que será usado em tempo de execução." -#: ../../library/compileall.rst:152 +#: ../../library/compileall.rst:159 msgid "Public functions" msgstr "Funções públicas" -#: ../../library/compileall.rst:156 +#: ../../library/compileall.rst:163 msgid "" "Recursively descend the directory tree named by *dir*, compiling all :file:`." "py` files along the way. Return a true value if all the files compiled " @@ -291,7 +306,7 @@ msgstr "" "verdadeiro se todos os arquivos forem compilados com êxito e um valor falso " "caso contrário." -#: ../../library/compileall.rst:160 +#: ../../library/compileall.rst:167 msgid "" "The *maxlevels* parameter is used to limit the depth of the recursion; it " "defaults to ``sys.getrecursionlimit()``." @@ -299,7 +314,7 @@ msgstr "" "O parâmetro *maxlevels* é usado para limitar a profundidade da recursão; o " "padrão é ``sys.getrecursionlimit()``." -#: ../../library/compileall.rst:163 +#: ../../library/compileall.rst:170 msgid "" "If *ddir* is given, it is prepended to the path to each file being compiled " "for use in compilation time tracebacks, and is also compiled in to the byte-" @@ -313,7 +328,7 @@ msgstr "" "outras mensagens nos casos em que o arquivo de origem não existe no momento " "em que o arquivo de bytecode é executado." -#: ../../library/compileall.rst:169 +#: ../../library/compileall.rst:176 msgid "" "If *force* is true, modules are re-compiled even if the timestamps are up to " "date." @@ -321,7 +336,7 @@ msgstr "" "Se *force* for verdadeiro, os módulos serão recompilados, mesmo que os " "carimbos de data e hora estejam atualizados." -#: ../../library/compileall.rst:172 +#: ../../library/compileall.rst:179 msgid "" "If *rx* is given, its ``search`` method is called on the complete path to " "each file considered for compilation, and if it returns a true value, the " @@ -334,7 +349,7 @@ msgstr "" "arquivos correspondendo a uma expressão regular, dado como um objeto :ref:" "`re.Pattern `." -#: ../../library/compileall.rst:177 ../../library/compileall.rst:254 +#: ../../library/compileall.rst:184 ../../library/compileall.rst:261 msgid "" "If *quiet* is ``False`` or ``0`` (the default), the filenames and other " "information are printed to standard out. Set to ``1``, only errors are " @@ -344,7 +359,7 @@ msgstr "" "informações serão impressos com o padrão. Definido como ``1``, apenas os " "erros são impressos. Definido como ``2``, toda a saída é suprimida." -#: ../../library/compileall.rst:181 ../../library/compileall.rst:258 +#: ../../library/compileall.rst:188 ../../library/compileall.rst:265 msgid "" "If *legacy* is true, byte-code files are written to their legacy locations " "and names, which may overwrite byte-code files created by another version of " @@ -358,7 +373,7 @@ msgstr "" "locais e nomes do :pep:`3147`, o que permite que arquivos de bytecodes de " "várias versões do Python coexistam." -#: ../../library/compileall.rst:187 ../../library/compileall.rst:264 +#: ../../library/compileall.rst:194 ../../library/compileall.rst:271 msgid "" "*optimize* specifies the optimization level for the compiler. It is passed " "to the built-in :func:`compile` function. Accepts also a sequence of " @@ -370,7 +385,7 @@ msgstr "" "níveis de otimização que levam a várias compilações de um arquivo :file:`." "py` em uma chamada." -#: ../../library/compileall.rst:191 +#: ../../library/compileall.rst:198 msgid "" "The argument *workers* specifies how many workers are used to compile files " "in parallel. The default is to not use multiple workers. If the platform " @@ -386,7 +401,7 @@ msgstr "" "de núcleos no sistema é usado. Se *workers* for menor que ``0``, a :exc:" "`ValueError` será levantada." -#: ../../library/compileall.rst:198 ../../library/compileall.rst:268 +#: ../../library/compileall.rst:205 ../../library/compileall.rst:275 msgid "" "*invalidation_mode* should be a member of the :class:`py_compile." "PycInvalidationMode` enum and controls how the generated pycs are " @@ -396,7 +411,7 @@ msgstr "" "PycInvalidationMode` e controla como os pycs gerados são invalidados em " "tempo de execução." -#: ../../library/compileall.rst:202 ../../library/compileall.rst:272 +#: ../../library/compileall.rst:209 ../../library/compileall.rst:279 msgid "" "The *stripdir*, *prependdir* and *limit_sl_dest* arguments correspond to the " "``-s``, ``-p`` and ``-e`` options described above. They may be specified as " @@ -406,7 +421,7 @@ msgstr "" "opções ``-s``, ``-p`` e ``-e`` descrita acima. eles podem ser especificados " "como ``str`` ou :py:class:`os.PathLike`." -#: ../../library/compileall.rst:206 ../../library/compileall.rst:276 +#: ../../library/compileall.rst:213 ../../library/compileall.rst:283 msgid "" "If *hardlink_dupes* is true and two ``.pyc`` files with different " "optimization level have the same content, use hard links to consolidate " @@ -416,21 +431,21 @@ msgstr "" "otimização diferente tiverem o mesmo conteúdo, usa links físicos para " "consolidar arquivos duplicados." -#: ../../library/compileall.rst:209 ../../library/compileall.rst:307 +#: ../../library/compileall.rst:216 ../../library/compileall.rst:314 msgid "Added the *legacy* and *optimize* parameter." msgstr "Adicionado os parâmetros *legacy* e *optimize*." -#: ../../library/compileall.rst:212 +#: ../../library/compileall.rst:219 msgid "Added the *workers* parameter." msgstr "Adicionado o parâmetro *workers*." -#: ../../library/compileall.rst:215 ../../library/compileall.rst:281 -#: ../../library/compileall.rst:310 +#: ../../library/compileall.rst:222 ../../library/compileall.rst:288 +#: ../../library/compileall.rst:317 msgid "*quiet* parameter was changed to a multilevel value." msgstr "O parâmetro *quiet* foi alterado para um valor multinível." -#: ../../library/compileall.rst:218 ../../library/compileall.rst:284 -#: ../../library/compileall.rst:313 +#: ../../library/compileall.rst:225 ../../library/compileall.rst:291 +#: ../../library/compileall.rst:320 msgid "" "The *legacy* parameter only writes out ``.pyc`` files, not ``.pyo`` files no " "matter what the value of *optimize* is." @@ -438,28 +453,28 @@ msgstr "" "O parâmetro *legacy* grava apenas arquivos ``.pyc``, não os arquivos ``." "pyo``, independentemente do valor de *optimize*." -#: ../../library/compileall.rst:222 +#: ../../library/compileall.rst:229 msgid "Accepts a :term:`path-like object`." msgstr "Aceita um :term:`objeto caminho ou similar`." -#: ../../library/compileall.rst:225 ../../library/compileall.rst:288 -#: ../../library/compileall.rst:317 +#: ../../library/compileall.rst:232 ../../library/compileall.rst:295 +#: ../../library/compileall.rst:324 msgid "The *invalidation_mode* parameter was added." msgstr "O parâmetro *invalidation_mode* foi adicionado." -#: ../../library/compileall.rst:228 ../../library/compileall.rst:291 -#: ../../library/compileall.rst:320 +#: ../../library/compileall.rst:235 ../../library/compileall.rst:298 +#: ../../library/compileall.rst:327 msgid "" "The *invalidation_mode* parameter's default value is updated to ``None``." msgstr "" "O valor padrão do parâmetro *invalidation_mode* é atualizado para ``None``." -#: ../../library/compileall.rst:231 +#: ../../library/compileall.rst:238 msgid "Setting *workers* to 0 now chooses the optimal number of cores." msgstr "" "A definição de *workers* como 0 agora escolhe o número ideal de núcleos." -#: ../../library/compileall.rst:234 +#: ../../library/compileall.rst:241 msgid "" "Added *stripdir*, *prependdir*, *limit_sl_dest* and *hardlink_dupes* " "arguments. Default value of *maxlevels* was changed from ``10`` to ``sys." @@ -469,7 +484,7 @@ msgstr "" "*hardlink_dupes*. O valor padrão de *maxlevels* foi alterado de ``10`` para " "``sys.getrecursionlimit()``" -#: ../../library/compileall.rst:240 +#: ../../library/compileall.rst:247 msgid "" "Compile the file with path *fullname*. Return a true value if the file " "compiled successfully, and a false value otherwise." @@ -477,7 +492,7 @@ msgstr "" "Compila o arquivo com o caminho *fullname*. Retorna um valor verdadeiro se o " "arquivo compilado com êxito e um valor falso caso contrário." -#: ../../library/compileall.rst:243 +#: ../../library/compileall.rst:250 msgid "" "If *ddir* is given, it is prepended to the path to the file being compiled " "for use in compilation time tracebacks, and is also compiled in to the byte-" @@ -491,7 +506,7 @@ msgstr "" "outras mensagens nos casos em que o arquivo fonte não existe no momento em " "que o arquivo de bytecode é executado." -#: ../../library/compileall.rst:249 +#: ../../library/compileall.rst:256 msgid "" "If *rx* is given, its ``search`` method is passed the full path name to the " "file being compiled, and if it returns a true value, the file is not " @@ -505,7 +520,7 @@ msgstr "" "pode ser usado para excluir arquivos correspondendo a uma expressão regular, " "dado como um objeto :ref:`re.Pattern `." -#: ../../library/compileall.rst:294 +#: ../../library/compileall.rst:301 msgid "" "Added *stripdir*, *prependdir*, *limit_sl_dest* and *hardlink_dupes* " "arguments." @@ -513,7 +528,7 @@ msgstr "" "Adicionados os argumentos *stripdir*, *prependdir*, *limit_sl_dest* e " "*hardlink_dupes*." -#: ../../library/compileall.rst:299 +#: ../../library/compileall.rst:306 msgid "" "Byte-compile all the :file:`.py` files found along ``sys.path``. Return a " "true value if all the files compiled successfully, and a false value " @@ -523,7 +538,7 @@ msgstr "" "longo de ``sys.path``. Retorna um valor verdadeiro se todos os arquivos " "forem compilados com êxito e um valor falso caso contrário." -#: ../../library/compileall.rst:302 +#: ../../library/compileall.rst:309 msgid "" "If *skip_curdir* is true (the default), the current directory is not " "included in the search. All other parameters are passed to the :func:" @@ -535,7 +550,7 @@ msgstr "" "func:`compile_dir`. Note que, ao contrário das outras funções de compilação, " "``maxlevels`` é padronizado como ``0``." -#: ../../library/compileall.rst:323 +#: ../../library/compileall.rst:330 msgid "" "To force a recompile of all the :file:`.py` files in the :file:`Lib/` " "subdirectory and all its subdirectories::" @@ -543,10 +558,36 @@ 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:340 +#: ../../library/compileall.rst:333 +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:347 msgid "Module :mod:`py_compile`" msgstr "Módulo :mod:`py_compile`" -#: ../../library/compileall.rst:341 +#: ../../library/compileall.rst:348 msgid "Byte-compile a single source file." msgstr "Compila para bytecode um único arquivo fonte." diff --git a/library/concurrency.po b/library/concurrency.po index e4df7e60d..efd35829a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..18cde5c7e 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -162,9 +163,20 @@ msgstr "" #: ../../library/concurrent.futures.rst:95 msgid "" -"You can avoid having to call this method explicitly if you use the :keyword:" -"`with` statement, which will shutdown the :class:`Executor` (waiting as if :" -"meth:`Executor.shutdown` were called with *wait* set to ``True``)::" +"You can avoid having to call this method explicitly if you use the executor " +"as a :term:`context manager` via the :keyword:`with` statement, which will " +"shutdown the :class:`Executor` (waiting as if :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 @@ -187,10 +199,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* " @@ -233,7 +276,7 @@ msgid "" msgstr "" #: ../../library/concurrent.futures.rst:179 -#: ../../library/concurrent.futures.rst:287 +#: ../../library/concurrent.futures.rst:292 msgid "Added the *initializer* and *initargs* arguments." msgstr "" @@ -261,6 +304,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```" @@ -288,7 +362,15 @@ msgid "" "submitted to a :class:`ProcessPoolExecutor` will result in deadlock." msgstr "" -#: ../../library/concurrent.futures.rst:248 +#: ../../library/concurrent.futures.rst:246 +msgid "" +"Note that the restrictions on functions and arguments needing to picklable " +"as per :class:`multiprocessing.Process` apply when using :meth:`~Executor." +"submit` and :meth:`~Executor.map` on a :class:`ProcessPoolExecutor`. A " +"function defined in a REPL or a lambda should not be expected to work." +msgstr "" + +#: ../../library/concurrent.futures.rst:253 msgid "" "An :class:`Executor` subclass that executes calls asynchronously using a " "pool of at most *max_workers* processes. If *max_workers* is ``None`` or " @@ -303,7 +385,7 @@ msgid "" "`multiprocessing-start-methods`." msgstr "" -#: ../../library/concurrent.futures.rst:262 +#: ../../library/concurrent.futures.rst:267 msgid "" "*initializer* is an optional callable that is called at the start of each " "worker process; *initargs* is a tuple of arguments passed to the " @@ -312,7 +394,7 @@ msgid "" "well as any attempt to submit more jobs to the pool." msgstr "" -#: ../../library/concurrent.futures.rst:268 +#: ../../library/concurrent.futures.rst:273 msgid "" "*max_tasks_per_child* is an optional argument that specifies the maximum " "number of tasks a single process can execute before it will exit and be " @@ -323,7 +405,7 @@ msgid "" "with the \"fork\" start method." msgstr "" -#: ../../library/concurrent.futures.rst:276 +#: ../../library/concurrent.futures.rst:281 msgid "" "When one of the worker processes terminates abruptly, a :exc:`~concurrent." "futures.process.BrokenProcessPool` error is now raised. Previously, " @@ -331,13 +413,13 @@ msgid "" "often freeze or deadlock." msgstr "" -#: ../../library/concurrent.futures.rst:283 +#: ../../library/concurrent.futures.rst:288 msgid "" "The *mp_context* argument was added to allow users to control the " "start_method for worker processes created by the pool." msgstr "" -#: ../../library/concurrent.futures.rst:290 +#: ../../library/concurrent.futures.rst:295 msgid "" "The default :mod:`multiprocessing` start method (see :ref:`multiprocessing-" "start-methods`) will change away from *fork* in Python 3.14. Code that " @@ -346,13 +428,13 @@ msgid "" "get_context(\"fork\")`` parameter." msgstr "" -#: ../../library/concurrent.futures.rst:297 +#: ../../library/concurrent.futures.rst:302 msgid "" "The *max_tasks_per_child* argument was added to allow users to control the " "lifetime of workers in the pool." msgstr "" -#: ../../library/concurrent.futures.rst:301 +#: ../../library/concurrent.futures.rst:306 msgid "" "On POSIX systems, if your application has multiple threads and the :mod:" "`multiprocessing` context uses the ``\"fork\"`` start method: The :func:`os." @@ -361,34 +443,70 @@ msgid "" "start method. See the :func:`os.fork` documentation for further explanation." msgstr "" -#: ../../library/concurrent.futures.rst:309 +#: ../../library/concurrent.futures.rst:314 msgid "" "*max_workers* uses :func:`os.process_cpu_count` by default, instead of :func:" "`os.cpu_count`." msgstr "" -#: ../../library/concurrent.futures.rst:316 +#: ../../library/concurrent.futures.rst:321 msgid "ProcessPoolExecutor Example" msgstr "" -#: ../../library/concurrent.futures.rst:354 +#: ../../library/concurrent.futures.rst:324 +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:359 msgid "Future Objects" msgstr "" -#: ../../library/concurrent.futures.rst:356 +#: ../../library/concurrent.futures.rst:361 msgid "" "The :class:`Future` class encapsulates the asynchronous execution of a " "callable. :class:`Future` instances are created by :meth:`Executor.submit`." msgstr "" -#: ../../library/concurrent.futures.rst:361 +#: ../../library/concurrent.futures.rst:366 msgid "" "Encapsulates the asynchronous execution of a callable. :class:`Future` " "instances are created by :meth:`Executor.submit` and should not be created " "directly except for testing." msgstr "" -#: ../../library/concurrent.futures.rst:367 +#: ../../library/concurrent.futures.rst:372 msgid "" "Attempt to cancel the call. If the call is currently being executed or " "finished running and cannot be cancelled then the method will return " @@ -396,22 +514,22 @@ msgid "" "``True``." msgstr "" -#: ../../library/concurrent.futures.rst:374 +#: ../../library/concurrent.futures.rst:379 msgid "Return ``True`` if the call was successfully cancelled." msgstr "" -#: ../../library/concurrent.futures.rst:378 +#: ../../library/concurrent.futures.rst:383 msgid "" "Return ``True`` if the call is currently being executed and cannot be " "cancelled." msgstr "" -#: ../../library/concurrent.futures.rst:383 +#: ../../library/concurrent.futures.rst:388 msgid "" "Return ``True`` if the call was successfully cancelled or finished running." msgstr "" -#: ../../library/concurrent.futures.rst:388 +#: ../../library/concurrent.futures.rst:393 msgid "" "Return the value returned by the call. If the call hasn't yet completed then " "this method will wait up to *timeout* seconds. If the call hasn't completed " @@ -420,19 +538,19 @@ msgid "" "no limit to the wait time." msgstr "" -#: ../../library/concurrent.futures.rst:395 -#: ../../library/concurrent.futures.rst:409 +#: ../../library/concurrent.futures.rst:400 +#: ../../library/concurrent.futures.rst:414 msgid "" "If the future is cancelled before completing then :exc:`.CancelledError` " "will be raised." msgstr "" -#: ../../library/concurrent.futures.rst:398 +#: ../../library/concurrent.futures.rst:403 msgid "" "If the call raised an exception, this method will raise the same exception." msgstr "" -#: ../../library/concurrent.futures.rst:402 +#: ../../library/concurrent.futures.rst:407 msgid "" "Return the exception raised by the call. If the call hasn't yet completed " "then this method will wait up to *timeout* seconds. If the call hasn't " @@ -441,18 +559,18 @@ msgid "" "``None``, there is no limit to the wait time." msgstr "" -#: ../../library/concurrent.futures.rst:412 +#: ../../library/concurrent.futures.rst:417 msgid "If the call completed without raising, ``None`` is returned." msgstr "" -#: ../../library/concurrent.futures.rst:416 +#: ../../library/concurrent.futures.rst:421 msgid "" "Attaches the callable *fn* to the future. *fn* will be called, with the " "future as its only argument, when the future is cancelled or finishes " "running." msgstr "" -#: ../../library/concurrent.futures.rst:420 +#: ../../library/concurrent.futures.rst:425 msgid "" "Added callables are called in the order that they were added and are always " "called in a thread belonging to the process that added them. If the " @@ -461,26 +579,26 @@ msgid "" "behavior is undefined." msgstr "" -#: ../../library/concurrent.futures.rst:426 +#: ../../library/concurrent.futures.rst:431 msgid "" "If the future has already completed or been cancelled, *fn* will be called " "immediately." msgstr "" -#: ../../library/concurrent.futures.rst:429 +#: ../../library/concurrent.futures.rst:434 msgid "" "The following :class:`Future` methods are meant for use in unit tests and :" "class:`Executor` implementations." msgstr "" -#: ../../library/concurrent.futures.rst:434 +#: ../../library/concurrent.futures.rst:439 msgid "" "This method should only be called by :class:`Executor` implementations " "before executing the work associated with the :class:`Future` and by unit " "tests." msgstr "" -#: ../../library/concurrent.futures.rst:438 +#: ../../library/concurrent.futures.rst:443 msgid "" "If the method returns ``False`` then the :class:`Future` was cancelled, i." "e. :meth:`Future.cancel` was called and returned ``True``. Any threads " @@ -488,49 +606,49 @@ msgid "" "or :func:`wait`) will be woken up." msgstr "" -#: ../../library/concurrent.futures.rst:443 +#: ../../library/concurrent.futures.rst:448 msgid "" "If the method returns ``True`` then the :class:`Future` was not cancelled " "and has been put in the running state, i.e. calls to :meth:`Future.running` " "will return ``True``." msgstr "" -#: ../../library/concurrent.futures.rst:447 +#: ../../library/concurrent.futures.rst:452 msgid "" "This method can only be called once and cannot be called after :meth:`Future." "set_result` or :meth:`Future.set_exception` have been called." msgstr "" -#: ../../library/concurrent.futures.rst:453 +#: ../../library/concurrent.futures.rst:458 msgid "" "Sets the result of the work associated with the :class:`Future` to *result*." msgstr "" -#: ../../library/concurrent.futures.rst:456 -#: ../../library/concurrent.futures.rst:469 +#: ../../library/concurrent.futures.rst:461 +#: ../../library/concurrent.futures.rst:474 msgid "" "This method should only be used by :class:`Executor` implementations and " "unit tests." msgstr "" -#: ../../library/concurrent.futures.rst:459 -#: ../../library/concurrent.futures.rst:472 +#: ../../library/concurrent.futures.rst:464 +#: ../../library/concurrent.futures.rst:477 msgid "" "This method raises :exc:`concurrent.futures.InvalidStateError` if the :class:" "`Future` is already done." msgstr "" -#: ../../library/concurrent.futures.rst:466 +#: ../../library/concurrent.futures.rst:471 msgid "" "Sets the result of the work associated with the :class:`Future` to the :" "class:`Exception` *exception*." msgstr "" -#: ../../library/concurrent.futures.rst:478 +#: ../../library/concurrent.futures.rst:483 msgid "Module Functions" msgstr "" -#: ../../library/concurrent.futures.rst:482 +#: ../../library/concurrent.futures.rst:487 msgid "" "Wait for the :class:`Future` instances (possibly created by different :class:" "`Executor` instances) given by *fs* to complete. Duplicate futures given to " @@ -541,14 +659,14 @@ msgid "" "running futures)." msgstr "" -#: ../../library/concurrent.futures.rst:490 +#: ../../library/concurrent.futures.rst:495 msgid "" "*timeout* can be used to control the maximum number of seconds to wait " "before returning. *timeout* can be an int or float. If *timeout* is not " "specified or ``None``, there is no limit to the wait time." msgstr "" -#: ../../library/concurrent.futures.rst:494 +#: ../../library/concurrent.futures.rst:499 msgid "" "*return_when* indicates when this function should return. It must be one of " "the following constants:" @@ -556,32 +674,32 @@ msgstr "" "*return_when* indica quando esta função deve retornar. Ele deve ser uma das " "seguintes constantes:" -#: ../../library/concurrent.futures.rst:500 +#: ../../library/concurrent.futures.rst:505 msgid "Constant" msgstr "Constante" -#: ../../library/concurrent.futures.rst:501 +#: ../../library/concurrent.futures.rst:506 msgid "Description" msgstr "Descrição" -#: ../../library/concurrent.futures.rst:504 +#: ../../library/concurrent.futures.rst:509 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/concurrent.futures.rst:507 +#: ../../library/concurrent.futures.rst:512 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/concurrent.futures.rst:512 +#: ../../library/concurrent.futures.rst:517 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/concurrent.futures.rst:516 +#: ../../library/concurrent.futures.rst:521 msgid "" "Returns an iterator over the :class:`Future` instances (possibly created by " "different :class:`Executor` instances) given by *fs* that yields futures as " @@ -594,55 +712,55 @@ msgid "" "*timeout* is not specified or ``None``, there is no limit to the wait time." msgstr "" -#: ../../library/concurrent.futures.rst:529 +#: ../../library/concurrent.futures.rst:534 msgid ":pep:`3148` -- futures - execute computations asynchronously" msgstr "" -#: ../../library/concurrent.futures.rst:530 +#: ../../library/concurrent.futures.rst:535 msgid "" "The proposal which described this feature for inclusion in the Python " "standard library." msgstr "" -#: ../../library/concurrent.futures.rst:535 +#: ../../library/concurrent.futures.rst:540 msgid "Exception classes" msgstr "" -#: ../../library/concurrent.futures.rst:541 +#: ../../library/concurrent.futures.rst:546 msgid "Raised when a future is cancelled." msgstr "" -#: ../../library/concurrent.futures.rst:545 +#: ../../library/concurrent.futures.rst:550 msgid "" "A deprecated alias of :exc:`TimeoutError`, raised when a future operation " "exceeds the given timeout." msgstr "" -#: ../../library/concurrent.futures.rst:550 +#: ../../library/concurrent.futures.rst:555 msgid "This class was made an alias of :exc:`TimeoutError`." msgstr "Esta classe foi feita como um apelido de :exc:`TimeoutError`." -#: ../../library/concurrent.futures.rst:555 +#: ../../library/concurrent.futures.rst:560 msgid "" "Derived from :exc:`RuntimeError`, this exception class is raised when an " "executor is broken for some reason, and cannot be used to submit or execute " "new tasks." msgstr "" -#: ../../library/concurrent.futures.rst:563 +#: ../../library/concurrent.futures.rst:568 msgid "" "Raised when an operation is performed on a future that is not allowed in the " "current state." msgstr "" -#: ../../library/concurrent.futures.rst:572 +#: ../../library/concurrent.futures.rst:577 msgid "" "Derived from :exc:`~concurrent.futures.BrokenExecutor`, this exception class " "is raised when one of the workers of a :class:`~concurrent.futures." "ThreadPoolExecutor` has failed initializing." msgstr "" -#: ../../library/concurrent.futures.rst:583 +#: ../../library/concurrent.futures.rst:588 msgid "" "Derived from :exc:`~concurrent.futures.BrokenExecutor` (formerly :exc:" "`RuntimeError`), this exception class is raised when one of the workers of " diff --git a/library/concurrent.po b/library/concurrent.po index d1890a4c6..7fc76327d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..fe93ca0e0 100644 --- a/library/configparser.po +++ b/library/configparser.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +51,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 +91,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 +141,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 +186,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 +194,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 +268,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 +284,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 +339,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 +371,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 +399,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 +411,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 +443,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 +464,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 +484,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 +530,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 +538,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 +550,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 " @@ -324,17 +558,104 @@ msgid "" msgstr "" "Os arquivos de configuração podem incluir comentários, prefixados por " "caracteres específicos (``#`` e ``;`` por padrão [1]_). Os comentários podem " -"aparecer sozinhos em uma linha vazia, possivelmente identados. [1]_" +"aparecer sozinhos em uma linha vazia, possivelmente indentados. [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 +663,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 +713,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 +751,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 +761,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 +777,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 +785,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 +863,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 +878,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 +890,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 +905,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 +929,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 +956,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 +972,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 +982,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 +1000,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 +1008,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 +1024,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 +1032,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 +1048,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 +1056,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 +1066,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 +1116,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 +1189,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 +1197,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 +1215,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 +1230,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 +1242,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 +1344,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 +1352,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 +1373,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 +1401,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 +1409,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 +1433,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 +1454,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 +1483,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 +1496,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 +1507,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 +1522,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 +1552,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 +1565,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 +1619,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 +1633,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 +1681,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 +1700,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 +1906,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 +1914,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 +1944,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 +1961,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 +1976,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 +1984,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 +2027,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 +2049,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 +2057,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 +2073,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 +2085,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 +2097,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 +2111,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 +2138,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 +2151,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 +2175,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 +2191,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 +2201,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 +2219,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 +2233,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 +2241,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 +2261,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 +2271,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 +2281,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 +2291,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 +2301,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 +2321,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 +2329,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 +2339,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 +2359,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 +2373,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 +2383,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 +2393,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 +2401,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 +2416,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 +2429,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 +2445,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 +2453,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 +2463,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 +2479,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 +2489,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 +2499,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 +2508,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 +2524,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 +2536,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 +2559,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 +2567,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 +2581,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 +2589,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 +2597,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 +2607,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 +2615,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 +2624,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 +2632,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 +2644,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 +2652,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 +2687,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..03a168c3b 100644 --- a/library/constants.po +++ b/library/constants.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,9 +58,9 @@ msgid "" "the :data:`~types.NoneType` type." msgstr "" "Um objeto frequentemente usado para representar a ausência de um valor, como " -"quando os argumentos padrão não são passados para uma função. As atribuições " -"a ``None`` são ilegais e levantam :exc:`SyntaxError`. ``None`` é a única " -"instância do tipo :data:`~types.NoneType`." +"quando os argumentos padrões não são passados para uma função. As " +"atribuições a ``None`` são ilegais e levantam :exc:`SyntaxError`. ``None`` é " +"a única instância do tipo :data:`~types.NoneType`." #: ../../library/constants.rst:30 msgid "" @@ -108,15 +107,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,19 +127,19 @@ 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 " -"types. ``Ellipsis`` is the sole instance of the :data:`types.EllipsisType` " -"type." +"The same as the ellipsis literal \"``...``\", an object frequently used to " +"indicate that something is omitted. Assignment to ``Ellipsis`` is possible, " +"but assignment to ``...`` raises a :exc:`SyntaxError`. ``Ellipsis`` is the " +"sole instance of the :data:`types.EllipsisType` type." msgstr "" -"O mesmo que as reticências literais \"``...``\". Valor especial usado " -"principalmente em conjunto com a sintaxe de divisão estendida para tipos de " -"dados de contêiner definidos pelo usuário. ``Ellipsis`` é a única instância " -"do tipo :data:`types.EllipsisType`." +"O mesmo que o literal de reticências \"``...``\", um objeto frequentemente " +"usado para indicar que algo foi omitido. A atribuição a ``Ellipsis`` é " +"possível, mas a atribuição a ``...`` levanta um :exc:`SyntaxError`. " +"``Ellipsis`` é a única instância do tipo :data:`types.EllipsisType`." -#: ../../library/constants.rst:71 +#: ../../library/constants.rst:73 msgid "" "This constant is true if Python was not started with an :option:`-O` option. " "See also the :keyword:`assert` statement." @@ -147,7 +147,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:79 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 +158,11 @@ msgstr "" "levantam :exc:`SyntaxError` ), para que possam ser consideradas " "\"verdadeiras\" constantes." -#: ../../library/constants.rst:83 +#: ../../library/constants.rst:87 msgid "Constants added by the :mod:`site` module" msgstr "Constantes adicionadas pelo módulo :mod:`site`" -#: ../../library/constants.rst:85 +#: ../../library/constants.rst:89 msgid "" "The :mod:`site` module (which is imported automatically during startup, " "except if the :option:`-S` command-line option is given) adds several " @@ -175,17 +175,30 @@ msgstr "" "úteis para o console do interpretador interativo e não devem ser usados em " "programas." -#: ../../library/constants.rst:93 +#: ../../library/constants.rst:97 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 " -"exit code." +"EOF) to exit\", and when accessed directly in the interactive interpreter or " +"called as functions, raise :exc:`SystemExit` with the specified exit code." msgstr "" -"Objetos que, quando impressos, imprimem uma mensagem como \"Use quit() or " -"Ctrl-D (i.e. EOF) to exit\" e, quando chamados, levantam :exc:`SystemExit` " -"com o código de saída especificado." +"Objetos que, quando exibidos, exibem uma mensagem como \"Use quit() or Ctrl-" +"D (i.e. EOF) to exit\" e, quando acessados diretamente no interpretador " +"interativo ou chamados como funções, levantam :exc:`SystemExit` com o código " +"de saída especificado." -#: ../../library/constants.rst:100 +#: ../../library/constants.rst:105 +msgid "" +"Object that when printed, prints the message \"Type help() for interactive " +"help, or help(object) for help about object.\", and when accessed directly " +"in the interactive interpreter, invokes the built-in help system (see :func:" +"`help`)." +msgstr "" +"Objeto que, quando exibido, exibe a mensagem \"Type help() for interactive " +"help, or help(object) for help about object.\" e, quando acessado " +"diretamente no interpretador interativo, invoca o sistema de ajuda embutido " +"(veja :func:`help`)." + +#: ../../library/constants.rst:113 msgid "" "Objects that when printed or called, print the text of copyright or credits, " "respectively." @@ -193,7 +206,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:118 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 +216,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" +msgstr "literal de reticências" diff --git a/library/contextlib.po b/library/contextlib.po index d9470b687..e38b39e64 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..f84d43147 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..ee03cddb6 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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)." @@ -230,16 +227,16 @@ msgstr "" "Este método deve criar um novo objeto do mesmo tipo, substituindo campos por " "valores de *changes*." -#: ../../library/copy.rst:128 +#: ../../library/copy.rst:130 msgid "Module :mod:`pickle`" msgstr "Módulo :mod:`pickle`" -#: ../../library/copy.rst:129 +#: ../../library/copy.rst:131 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..d38f11768 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..3c9a646ae --- /dev/null +++ b/library/crypt.po @@ -0,0 +1,59 @@ +# 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: +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-10-13 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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`, or :pypi:`argon2-cffi`. 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` ou :pypi:`argon2-cffi`. 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..2589d83c4 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..154f3fdab 100644 --- a/library/csv.po +++ b/library/csv.po @@ -1,28 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +86,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 +114,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 " @@ -132,20 +130,38 @@ msgstr "" #: ../../library/csv.rst:72 msgid "" "Each row read from the csv file is returned as a list of strings. No " -"automatic data type conversion is performed unless the ``QUOTE_NONNUMERIC`` " -"format option is specified (in which case unquoted fields are transformed " -"into floats)." +"automatic data type conversion is performed unless the :data:" +"`QUOTE_NONNUMERIC` format option is specified (in which case unquoted fields " +"are transformed into floats)." msgstr "" -"Cada linha lida no arquivo csv é retornada como uma lista de cadeias. " +"Cada linha lida no arquivo csv é retornada como uma lista de strings. " "Nenhuma conversão automática de tipo de dados é executada, a menos que a " -"opção de formato ``QUOTE_NONNUMERIC`` seja especificada (nesse caso, os " +"opção de formato :data:`QUOTE_NONNUMERIC` seja especificada (nesse caso, os " "campos não citados são transformados em pontos flutuantes)." -#: ../../library/csv.rst:76 ../../library/csv.rst:106 ../../library/csv.rst:181 -#: ../../library/csv.rst:219 +#: ../../library/csv.rst:76 ../../library/csv.rst:106 ../../library/csv.rst:182 +#: ../../library/csv.rst:220 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 +199,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 " @@ -219,7 +251,7 @@ msgstr "" msgid "Return the names of all registered dialects." msgstr "Retorna os nomes de todos os dialetos registrados" -#: ../../library/csv.rst:144 +#: ../../library/csv.rst:145 msgid "" "Returns the current maximum field size allowed by the parser. If *new_limit* " "is given, this becomes the new limit." @@ -227,11 +259,11 @@ msgstr "" "Retorna o tamanho máximo atual do campo permitido pelo analisador sintático. " "Se *new_limit* for fornecido, este se tornará o novo limite." -#: ../../library/csv.rst:148 +#: ../../library/csv.rst:149 msgid "The :mod:`csv` module defines the following classes:" msgstr "O módulo :mod:`csv` define as seguintes classes:" -#: ../../library/csv.rst:153 +#: ../../library/csv.rst:154 msgid "" "Create an object that operates like a regular reader but maps the " "information in each row to a :class:`dict` whose keys are given by the " @@ -241,7 +273,7 @@ msgstr "" "em cada linha para :class:`dict` cujas chaves são fornecidas pelo parâmetro " "opcional *fieldnames*." -#: ../../library/csv.rst:157 +#: ../../library/csv.rst:158 msgid "" "The *fieldnames* parameter is a :term:`sequence`. If *fieldnames* is " "omitted, the values in the first row of file *f* will be used as the " @@ -257,7 +289,7 @@ msgstr "" "Independentemente de como os nomes de campo são determinados, o dicionário " "preserva sua ordem original." -#: ../../library/csv.rst:164 +#: ../../library/csv.rst:165 msgid "" "If a row has more fields than fieldnames, the remaining data is put in a " "list and stored with the fieldname specified by *restkey* (which defaults to " @@ -271,7 +303,7 @@ msgstr "" "tiver menos campos que nomes de campo, os valores ausentes serão preenchidos " "com o valor *restval* (o padrão é ``None``)." -#: ../../library/csv.rst:170 +#: ../../library/csv.rst:171 msgid "" "All other optional or keyword arguments are passed to the underlying :class:" "`reader` instance." @@ -279,7 +311,7 @@ msgstr "" "Todos os outros argumentos nomeados ou opcionais são passados para a " "instância subjacente de :class:`reader`." -#: ../../library/csv.rst:173 ../../library/csv.rst:217 +#: ../../library/csv.rst:174 ../../library/csv.rst:218 msgid "" "If the argument passed to *fieldnames* is an iterator, it will be coerced to " "a :class:`list`." @@ -287,15 +319,41 @@ msgstr "" "Se o argumento passado para *fieldnames* for um iterador, ele será " "convertido para uma :class:`list`." -#: ../../library/csv.rst:175 +#: ../../library/csv.rst:176 msgid "Returned rows are now of type :class:`OrderedDict`." msgstr "Linhas retornadas agora são do tipo :class:`OrderedDict`." -#: ../../library/csv.rst:178 +#: ../../library/csv.rst:179 msgid "Returned rows are now of type :class:`dict`." msgstr "As linhas retornadas agora são do tipo :class:`dict`." -#: ../../library/csv.rst:199 +#: ../../library/csv.rst:184 +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:200 msgid "" "Create an object which operates like a regular writer but maps dictionaries " "onto output rows. The *fieldnames* parameter is a :mod:`sequence " @@ -324,7 +382,7 @@ msgstr "" "Quaisquer outros argumentos nomeados ou opcionais são passados para a " "instância subjacente de :class:`writer`." -#: ../../library/csv.rst:214 +#: ../../library/csv.rst:215 msgid "" "Note that unlike the :class:`DictReader` class, the *fieldnames* parameter " "of the :class:`DictWriter` class is not optional." @@ -332,7 +390,31 @@ msgstr "" "Observe que, diferentemente da classe :class:`DictReader`, o parâmetro " "*fieldnames* da classe :class:`DictWriter` não é opcional." -#: ../../library/csv.rst:235 +#: ../../library/csv.rst:222 +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:236 msgid "" "The :class:`Dialect` class is a container class whose attributes contain " "information for how to handle doublequotes, whitespace, delimiters, etc. Due " @@ -347,7 +429,7 @@ msgstr "" "instâncias de :class:`Dialect` definem como as instâncias :class:`reader` e :" "class:`writer` se comportam." -#: ../../library/csv.rst:241 +#: ../../library/csv.rst:242 msgid "" "All available :class:`Dialect` names are returned by :func:`list_dialects`, " "and they can be registered with specific :class:`reader` and :class:`writer` " @@ -358,7 +440,19 @@ msgstr "" "class:`writer` específicas através de suas funções inicializadoras " "(``__init__``) como esta::" -#: ../../library/csv.rst:253 +#: ../../library/csv.rst:246 +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:254 msgid "" "The :class:`excel` class defines the usual properties of an Excel-generated " "CSV file. It is registered with the dialect name ``'excel'``." @@ -366,7 +460,7 @@ msgstr "" "A classe :class:`excel` define as propriedades usuais de um arquivo CSV " "gerado pelo Excel. Ele é registrado com o nome do dialeto ``'excel'``." -#: ../../library/csv.rst:259 +#: ../../library/csv.rst:260 msgid "" "The :class:`excel_tab` class defines the usual properties of an Excel-" "generated TAB-delimited file. It is registered with the dialect name " @@ -376,7 +470,7 @@ msgstr "" "delimitado por TAB gerado pelo Excel. Ela é registrado com o nome do dialeto " "``'excel-tab'``." -#: ../../library/csv.rst:265 +#: ../../library/csv.rst:266 msgid "" "The :class:`unix_dialect` class defines the usual properties of a CSV file " "generated on UNIX systems, i.e. using ``'\\n'`` as line terminator and " @@ -387,16 +481,16 @@ msgstr "" "linha e citando todos os campos. É registrado com o nome do dialeto " "``'unix'``." -#: ../../library/csv.rst:274 +#: ../../library/csv.rst:275 msgid "The :class:`Sniffer` class is used to deduce the format of a CSV file." msgstr "" "A classe :class:`Sniffer` é usada para deduzir o formato de um arquivo CSV." -#: ../../library/csv.rst:276 +#: ../../library/csv.rst:277 msgid "The :class:`Sniffer` class provides two methods:" msgstr "A classe :class:`Sniffer` fornece dois métodos:" -#: ../../library/csv.rst:280 +#: ../../library/csv.rst:281 msgid "" "Analyze the given *sample* and return a :class:`Dialect` subclass reflecting " "the parameters found. If the optional *delimiters* parameter is given, it " @@ -407,7 +501,7 @@ msgstr "" "for fornecido, ele será interpretado como uma string contendo possíveis " "caracteres válidos de delimitador." -#: ../../library/csv.rst:288 +#: ../../library/csv.rst:289 msgid "" "Analyze the sample text (presumed to be in CSV format) and return :const:" "`True` if the first row appears to be a series of column headers. Inspecting " @@ -419,11 +513,11 @@ msgstr "" "Inspecionando cada coluna, um dos dois critérios principais será considerado " "para estimar se a amostra contém um cabeçalho:" -#: ../../library/csv.rst:293 +#: ../../library/csv.rst:294 msgid "the second through n-th rows contain numeric values" msgstr "da segunda até a enésima linha contém valores numéricos" -#: ../../library/csv.rst:294 +#: ../../library/csv.rst:295 msgid "" "the second through n-th rows contain strings where at least one value's " "length differs from that of the putative header of that column." @@ -431,15 +525,13 @@ msgstr "" "da segunda até a enésima linha contém strings em que pelo menos o " "comprimento de um valor difere daquele do cabeçalho putativo dessa coluna." -#: ../../library/csv.rst:297 +#: ../../library/csv.rst:298 msgid "" -"Twenty rows after the first row are sampled; if more than half of columns + " -"rows meet the criteria, :const:`True` is returned." +"Twenty-one rows after the header are sampled; if more than half of the " +"columns + rows meet the criteria, :const:`True` is returned." msgstr "" -"Vinte linhas após a primeira linha são amostradas; se mais da metade das " -"colunas + linhas atenderem aos critérios, :const:`True` será retornado." -#: ../../library/csv.rst:302 +#: ../../library/csv.rst:303 msgid "" "This method is a rough heuristic and may produce both false positives and " "negatives." @@ -447,55 +539,85 @@ msgstr "" "Este método é uma heurística aproximada e pode produzir falsos positivos e " "negativos." -#: ../../library/csv.rst:305 +#: ../../library/csv.rst:306 msgid "An example for :class:`Sniffer` use::" msgstr "Um exemplo para uso de :class:`Sniffer`::" -#: ../../library/csv.rst:316 +#: ../../library/csv.rst:308 +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:317 msgid "The :mod:`csv` module defines the following constants:" msgstr "O módulo :mod:`csv` define as seguintes constantes:" -#: ../../library/csv.rst:320 +#: ../../library/csv.rst:321 msgid "Instructs :class:`writer` objects to quote all fields." msgstr "Instrui objetos :class:`writer` a colocar aspas em todos os campos." -#: ../../library/csv.rst:325 +#: ../../library/csv.rst:326 msgid "" "Instructs :class:`writer` objects to only quote those fields which contain " -"special characters such as *delimiter*, *quotechar* or any of the characters " -"in *lineterminator*." +"special characters such as *delimiter*, *quotechar*, ``'\\r'``, ``'\\n'`` or " +"any of the characters in *lineterminator*." msgstr "" "Instrui objetos :class:`writer` a colocar aspas apenas nos campos que contêm " -"caracteres especiais como *delimiters*, *quotechar* ou qualquer um dos " -"caracteres em *lineterminator*." +"caracteres especiais como *delimiters*, *quotechar*, ``'\\r'``, ``'\\n'`` ou " +"qualquer um dos caracteres em *lineterminator*." -#: ../../library/csv.rst:332 +#: ../../library/csv.rst:333 msgid "Instructs :class:`writer` objects to quote all non-numeric fields." msgstr "" "Instrui objetos :class:`writer` a colocar aspas em todos os campos não " "numéricos." -#: ../../library/csv.rst:334 +#: ../../library/csv.rst:335 msgid "" -"Instructs :class:`reader` objects to convert all non-quoted fields to type " -"*float*." +"Instructs :class:`reader` objects to convert all non-quoted fields to type :" +"class:`float`." msgstr "" "Instrui objetos :class:`reader` a converter todos os campos não envoltos por " -"aspas no tipo *float*." +"aspas no tipo :class:`float`." -#: ../../library/csv.rst:339 +#: ../../library/csv.rst:338 msgid "" -"Instructs :class:`writer` objects to never quote fields. When the current " -"*delimiter* occurs in output data it is preceded by the current *escapechar* " -"character. If *escapechar* is not set, the writer will raise :exc:`Error` " -"if any characters that require escaping are encountered." +"Some numeric types, such as :class:`bool`, :class:`~fractions.Fraction`, or :" +"class:`~enum.IntEnum`, have a string representation that cannot be converted " +"to :class:`float`. They cannot be read in the :data:`QUOTE_NONNUMERIC` and :" +"data:`QUOTE_STRINGS` modes." +msgstr "" +"Alguns tipos numéricos, como :class:`bool`, :class:`~fractions.Fraction` ou :" +"class:`~enum.IntEnum`, têm uma representação de string que não pode ser " +"convertida para :class:`float`. Eles não podem ser lidos nos modos :data:" +"`QUOTE_NONNUMERIC` e :data:`QUOTE_STRINGS`." + +#: ../../library/csv.rst:346 +msgid "" +"Instructs :class:`writer` objects to never quote fields. When the current " +"*delimiter*, *quotechar*, *escapechar*, ``'\\r'``, ``'\\n'`` or any of the " +"characters in *lineterminator* occurs in output data it is preceded by the " +"current *escapechar* character. If *escapechar* is not set, the writer will " +"raise :exc:`Error` if any characters that require escaping are encountered. " +"Set *quotechar* to ``None`` to prevent its escaping." msgstr "" "Instrui objetos :class:`writer` a nunca colocar aspas nos campos. Quando o " -"*delimiter* atual ocorre nos dados de saída, é precedido pelo caractere " -"*escapechar* atual. Se *escapeechar* não estiver definido, o escritor " -"levantará :exc:`Error` se algum caractere que exija escape for encontrado." +"*delimiter*, *quotechar*, *escapechar*, ``'\\r'``, ``'\\n'`` ou qualquer um " +"dos caracteres em *lineterminator* ocorre nos dados de saída, é precedido " +"pelo caractere *escapechar* atual. Se *escapeechar* não estiver definido, o " +"escritor levantará :exc:`Error` se algum caractere que exija escape for " +"encontrado. Defina *quotechar* para ``None`` para evitar seu escape." -#: ../../library/csv.rst:344 +#: ../../library/csv.rst:354 msgid "" "Instructs :class:`reader` objects to perform no special processing of quote " "characters." @@ -503,7 +625,7 @@ msgstr "" "Instrui objetos :class:`reader` a não executar nenhum processamento especial " "de caracteres de aspas." -#: ../../library/csv.rst:348 +#: ../../library/csv.rst:358 msgid "" "Instructs :class:`writer` objects to quote all fields which are not " "``None``. This is similar to :data:`QUOTE_ALL`, except that if a field " @@ -513,7 +635,7 @@ msgstr "" "``None``. Isso é semelhante a :data:`QUOTE_ALL`, exceto que se o valor de um " "campo for ``None``, uma string vazia (sem aspas) é escrita." -#: ../../library/csv.rst:352 +#: ../../library/csv.rst:362 msgid "" "Instructs :class:`reader` objects to interpret an empty (unquoted) field as " "``None`` and to otherwise behave as :data:`QUOTE_ALL`." @@ -521,7 +643,7 @@ msgstr "" "Instrui objetos :class:`reader` a interpretar um campo vazio (sem aspas) " "como ``None`` e a se comportar de outra forma como :data:`QUOTE_ALL`." -#: ../../library/csv.rst:359 +#: ../../library/csv.rst:369 msgid "" "Instructs :class:`writer` objects to always place quotes around fields which " "are strings. This is similar to :data:`QUOTE_NONNUMERIC`, except that if a " @@ -531,7 +653,7 @@ msgstr "" "que são strings. Isso é semelhante a :data:`QUOTE_NONNUMERIC`, exceto que se " "o valor de um campo for ``None``, uma string vazia (sem aspas) é escrita." -#: ../../library/csv.rst:363 +#: ../../library/csv.rst:373 msgid "" "Instructs :class:`reader` objects to interpret an empty (unquoted) string as " "``None`` and to otherwise behave as :data:`QUOTE_NONNUMERIC`." @@ -539,19 +661,19 @@ msgstr "" "Instrui objetos :class:`reader` a interpretar uma string vazia (sem aspas) " "como ``None`` e a se comportar de outra forma como :data:`QUOTE_NONNUMERIC`." -#: ../../library/csv.rst:368 +#: ../../library/csv.rst:378 msgid "The :mod:`csv` module defines the following exception:" msgstr "O módulo :mod:`csv` define a seguinte exceção:" -#: ../../library/csv.rst:373 +#: ../../library/csv.rst:383 msgid "Raised by any of the functions when an error is detected." msgstr "Levantada por qualquer uma das funções quando um erro é detectado." -#: ../../library/csv.rst:378 +#: ../../library/csv.rst:388 msgid "Dialects and Formatting Parameters" msgstr "Dialetos e parâmetros de formatação" -#: ../../library/csv.rst:380 +#: ../../library/csv.rst:390 msgid "" "To make it easier to specify the format of input and output records, " "specific formatting parameters are grouped together into dialects. A " @@ -573,17 +695,17 @@ msgstr "" "especificar parâmetros de formatação individuais, com os mesmos nomes dos " "atributos definidos abaixo para a classe :class:`Dialect`." -#: ../../library/csv.rst:390 +#: ../../library/csv.rst:400 msgid "Dialects support the following attributes:" msgstr "Os dialetos possuem suporte aos seguintes atributos:" -#: ../../library/csv.rst:395 +#: ../../library/csv.rst:405 msgid "" "A one-character string used to separate fields. It defaults to ``','``." msgstr "" "Uma string de um caractere usada para separar campos. O padrão é ``','``." -#: ../../library/csv.rst:400 +#: ../../library/csv.rst:410 msgid "" "Controls how instances of *quotechar* appearing inside a field should " "themselves be quoted. When :const:`True`, the character is doubled. When :" @@ -595,7 +717,7 @@ msgstr "" "Quando :const:`False`, o *escapechar* é usado como um prefixo para o " "*quotechar*. O padrão é :const:`True`." -#: ../../library/csv.rst:405 +#: ../../library/csv.rst:415 msgid "" "On output, if *doublequote* is :const:`False` and no *escapechar* is set, :" "exc:`Error` is raised if a *quotechar* is found in a field." @@ -604,25 +726,45 @@ msgstr "" "definido, :exc:`Error` é levantada se um *quotechar* é encontrado em um " "campo." -#: ../../library/csv.rst:411 +#: ../../library/csv.rst:421 +msgid "" +"A one-character string used by the writer to escape characters that require " +"escaping:" +msgstr "" +"Uma string de caracteres de um caractere usada pelo escritor para escapar " +"caracteres que exigem escape:" + +#: ../../library/csv.rst:424 msgid "" -"A one-character string used by the writer to escape the *delimiter* if " -"*quoting* is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* " -"is :const:`False`. On reading, the *escapechar* removes any special meaning " -"from the following character. It defaults to :const:`None`, which disables " -"escaping." +"the *delimiter*, the *quotechar*, ``'\\r'``, ``'\\n'`` and any of the " +"characters in *lineterminator* are escaped if *quoting* is set to :const:" +"`QUOTE_NONE`;" msgstr "" -"Uma string usada pelo escritor para escapar do *delimiter* se *quoting* " -"estiver definida como :const:`QUOTE_NONE` e o *quotechar* se *doublequote* " -"for :const:`False`. Na leitura, o *escapechar* remove qualquer significado " -"especial do caractere seguinte. O padrão é :const:`None`, que desativa o " -"escape." +"o *delimiter*, o *quotechar*, ``'\\r'``, ``'\\n'`` e qualquer um dos " +"caracteres em *lineterminator* são escapados se *quoting* estiver definido " +"como :const:`QUOTE_NONE`;" -#: ../../library/csv.rst:416 +#: ../../library/csv.rst:427 +msgid "the *quotechar* is escaped if *doublequote* is :const:`False`;" +msgstr "o *quotechar* é escapado se *doublequote* for :const:`False`;" + +#: ../../library/csv.rst:428 +msgid "the *escapechar* itself." +msgstr "o *escapechar* em si." + +#: ../../library/csv.rst:430 +msgid "" +"On reading, the *escapechar* removes any special meaning from the following " +"character. It defaults to :const:`None`, which disables escaping." +msgstr "" +"Na leitura, o *escapechar* remove qualquer significado especial do caractere " +"seguinte. O padrão é :const:`None`, o que desabilita o escape." + +#: ../../library/csv.rst:433 msgid "An empty *escapechar* is not allowed." msgstr "Um *escapechar* vazio não é permitido." -#: ../../library/csv.rst:421 +#: ../../library/csv.rst:438 msgid "" "The string used to terminate lines produced by the :class:`writer`. It " "defaults to ``'\\r\\n'``." @@ -630,7 +772,7 @@ msgstr "" "A string usada para terminar as linhas produzidas pelo :class:`writer`. O " "padrão é ``'\\r\\n'``." -#: ../../library/csv.rst:426 +#: ../../library/csv.rst:443 msgid "" "The :class:`reader` is hard-coded to recognise either ``'\\r'`` or ``'\\n'`` " "as end-of-line, and ignores *lineterminator*. This behavior may change in " @@ -640,39 +782,48 @@ msgstr "" "fim de linha e ignora *lineterminator*. Esse comportamento pode mudar no " "futuro." -#: ../../library/csv.rst:433 +#: ../../library/csv.rst:450 msgid "" "A one-character string used to quote fields containing special characters, " -"such as the *delimiter* or *quotechar*, or which contain new-line " -"characters. It defaults to ``'\"'``." -msgstr "" -"Uma string de um caractere usada para citar campos contendo caracteres " -"especiais, como *delimiter* ou *quotechar*, ou que contêm caracteres de nova " -"linha. O padrão é ``'\"'``." - -#: ../../library/csv.rst:437 +"such as the *delimiter* or the *quotechar*, or which contain new-line " +"characters (``'\\r'``, ``'\\n'`` or any of the characters in " +"*lineterminator*). It defaults to ``'\"'``. Can be set to ``None`` to " +"prevent escaping ``'\"'`` if *quoting* is set to :const:`QUOTE_NONE`." +msgstr "" +"Uma string de um caractere usada para colocar entre aspas campos que contêm " +"caracteres especiais, como o *delimiter* ou o *quotechar*, ou que contêm " +"caracteres de nova linha (``'\\r'``, ``'\\n'`` ou qualquer um dos caracteres " +"em *lineterminator*). O padrão é ``'\"'``. Pode ser definido como ``None`` " +"para evitar o escape de ``'\"'`` se *aspas* estiver definido como :const:" +"`QUOTE_NONE`." + +#: ../../library/csv.rst:457 msgid "An empty *quotechar* is not allowed." msgstr "Um *quotechar* vazio não é permitido." -#: ../../library/csv.rst:442 +#: ../../library/csv.rst:462 msgid "" "Controls when quotes should be generated by the writer and recognised by the " "reader. It can take on any of the :ref:`QUOTE_\\* constants ` and defaults to :const:`QUOTE_MINIMAL`." +"constants>` and defaults to :const:`QUOTE_MINIMAL` if *quotechar* is not " +"``None``, and :const:`QUOTE_NONE` otherwise." msgstr "" "Controla quando as aspas devem ser geradas pelo escritor e reconhecidas pelo " "leitor. Ele pode assumir qualquer uma das constantes :ref:`QUOTE_\\* " -"constants ` e o padrão é :const:`QUOTE_MINIMAL`." +"constants ` e o padrão é :const:`QUOTE_MINIMAL`. se " +"*quotechar* não for ``None`` e, do contrário, :const:`QUOTE_NONE`." -#: ../../library/csv.rst:449 +#: ../../library/csv.rst:470 msgid "" "When :const:`True`, spaces immediately following the *delimiter* are " -"ignored. The default is :const:`False`." +"ignored. The default is :const:`False`. When combining ``delimiter=' '`` " +"with ``skipinitialspace=True``, unquoted empty fields are not allowed." msgstr "" -"Quando :const:`True`, os espaços em branco imediatamente após o *delimiter* " -"são ignorados. O padrão é :const:`False`." +"Quando :const:`True`, os espaços imediatamente após o *delimitador* são " +"ignorados. O padrão é :const:`False`. Ao combinar ``delimiter=' '`` com " +"``skipinitialspace=True``, campos vazios sem aspas não são permitidos." -#: ../../library/csv.rst:455 +#: ../../library/csv.rst:477 msgid "" "When ``True``, raise exception :exc:`Error` on bad CSV input. The default is " "``False``." @@ -680,11 +831,11 @@ msgstr "" "Quando ``True``, levanta a exceção :exc:`Error` em uma entrada CSV ruim. O " "padrão é ``False``." -#: ../../library/csv.rst:461 +#: ../../library/csv.rst:483 msgid "Reader Objects" msgstr "Objetos Reader" -#: ../../library/csv.rst:463 +#: ../../library/csv.rst:485 msgid "" "Reader objects (:class:`DictReader` instances and objects returned by the :" "func:`reader` function) have the following public methods:" @@ -692,7 +843,7 @@ msgstr "" "Os objetos Reader (instâncias :class:`DictReader` e objetos retornados pela " "função :func:`reader`) têm os seguintes métodos públicos:" -#: ../../library/csv.rst:468 +#: ../../library/csv.rst:490 msgid "" "Return the next row of the reader's iterable object as a list (if the object " "was returned from :func:`reader`) or a dict (if it is a :class:`DictReader` " @@ -704,16 +855,16 @@ msgstr "" "class:`DictReader`), analisado de acordo com a :class:`Dialect` atual. " "Normalmente, você deve chamar isso de ``next(reader)``." -#: ../../library/csv.rst:474 +#: ../../library/csv.rst:496 msgid "Reader objects have the following public attributes:" msgstr "Os objetos Reader possuem os seguintes atributos públicos:" -#: ../../library/csv.rst:478 +#: ../../library/csv.rst:500 msgid "A read-only description of the dialect in use by the parser." msgstr "" "Uma descrição somente leitura do dialeto em uso pelo analisador sintático." -#: ../../library/csv.rst:483 +#: ../../library/csv.rst:505 msgid "" "The number of lines read from the source iterator. This is not the same as " "the number of records returned, as records can span multiple lines." @@ -721,11 +872,11 @@ msgstr "" "O número de linhas lidas no iterador de origem. Não é o mesmo que o número " "de registros retornados, pois os registros podem abranger várias linhas." -#: ../../library/csv.rst:487 +#: ../../library/csv.rst:509 msgid "DictReader objects have the following public attribute:" msgstr "Os objetos DictReader têm o seguinte atributo público:" -#: ../../library/csv.rst:491 +#: ../../library/csv.rst:513 msgid "" "If not passed as a parameter when creating the object, this attribute is " "initialized upon first access or when the first record is read from the file." @@ -734,11 +885,11 @@ msgstr "" "inicializado no primeiro acesso ou quando o primeiro registro for lido no " "arquivo." -#: ../../library/csv.rst:498 +#: ../../library/csv.rst:520 msgid "Writer Objects" msgstr "Objetos Writer" -#: ../../library/csv.rst:500 +#: ../../library/csv.rst:522 msgid "" ":class:`writer` objects (:class:`DictWriter` instances and objects returned " "by the :func:`writer` function) have the following public methods. A *row* " @@ -758,7 +909,7 @@ msgstr "" "problemas para outros programas que leem arquivos CSV (supondo que eles " "aceitem números complexos)." -#: ../../library/csv.rst:511 +#: ../../library/csv.rst:533 msgid "" "Write the *row* parameter to the writer's file object, formatted according " "to the current :class:`Dialect`. Return the return value of the call to the " @@ -768,11 +919,11 @@ msgstr "" "com a :class:`Dialect` atual. Retorna o valor de retorno da chamada ao " "método *write* do objeto arquivo subjacente." -#: ../../library/csv.rst:515 +#: ../../library/csv.rst:537 msgid "Added support of arbitrary iterables." msgstr "Adicionado suporte a iteráveis arbitrários." -#: ../../library/csv.rst:520 +#: ../../library/csv.rst:542 msgid "" "Write all elements in *rows* (an iterable of *row* objects as described " "above) to the writer's file object, formatted according to the current " @@ -782,19 +933,19 @@ msgstr "" "descrito acima) no objeto arquivo do escritor, formatado de acordo com o " "dialeto atual." -#: ../../library/csv.rst:524 +#: ../../library/csv.rst:546 msgid "Writer objects have the following public attribute:" msgstr "Os objetos Writer têm o seguinte atributo público:" -#: ../../library/csv.rst:529 +#: ../../library/csv.rst:551 msgid "A read-only description of the dialect in use by the writer." msgstr "Uma descrição somente leitura do dialeto em uso pelo escritor." -#: ../../library/csv.rst:532 +#: ../../library/csv.rst:554 msgid "DictWriter objects have the following public method:" msgstr "Os objetos DictWriter têm o seguinte método público:" -#: ../../library/csv.rst:537 +#: ../../library/csv.rst:559 msgid "" "Write a row with the field names (as specified in the constructor) to the " "writer's file object, formatted according to the current dialect. Return the " @@ -805,7 +956,7 @@ msgstr "" "atual. Retorna o valor de retorno da chamada :meth:`csvwriter.writerow` " "usada internamente." -#: ../../library/csv.rst:542 +#: ../../library/csv.rst:564 msgid "" ":meth:`writeheader` now also returns the value returned by the :meth:" "`csvwriter.writerow` method it uses internally." @@ -813,23 +964,63 @@ msgstr "" ":meth:`writeheader` agora também retorna o valor retornado pelo método :meth:" "`csvwriter.writerow` que ele usa internamente." -#: ../../library/csv.rst:550 +#: ../../library/csv.rst:572 msgid "Examples" msgstr "Exemplos" -#: ../../library/csv.rst:552 +#: ../../library/csv.rst:574 msgid "The simplest example of reading a CSV file::" msgstr "O exemplo mais simples de leitura de um arquivo CSV::" -#: ../../library/csv.rst:560 +#: ../../library/csv.rst:576 +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:582 msgid "Reading a file with an alternate format::" msgstr "Lendo um arquivo com um formato alternativo::" -#: ../../library/csv.rst:568 +#: ../../library/csv.rst:584 +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:590 msgid "The corresponding simplest possible writing example is::" msgstr "O exemplo de escrita possível mais simples possível é::" -#: ../../library/csv.rst:575 +#: ../../library/csv.rst:592 +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:597 msgid "" "Since :func:`open` is used to open a CSV file for reading, the file will by " "default be decoded into unicode using the system default encoding (see :func:" @@ -841,7 +1032,21 @@ msgstr "" "sistema (consulte :func:`locale.getencoding`). Para decodificar um arquivo " "usando uma codificação diferente, use o argumento ``encoding`` do open::" -#: ../../library/csv.rst:586 +#: ../../library/csv.rst:602 +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:608 msgid "" "The same applies to writing in something other than the system default " "encoding: specify the encoding argument when opening the output file." @@ -849,18 +1054,52 @@ msgstr "" "O mesmo se aplica à escrita em algo diferente da codificação padrão do " "sistema: especifique o argumento de codificação ao abrir o arquivo de saída." -#: ../../library/csv.rst:589 +#: ../../library/csv.rst:611 msgid "Registering a new dialect::" msgstr "Registrando um novo dialeto::" -#: ../../library/csv.rst:596 +#: ../../library/csv.rst:613 +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:618 msgid "" "A slightly more advanced use of the reader --- catching and reporting " "errors::" msgstr "" "Um uso um pouco mais avançado do leitor --- capturando e relatando erros::" -#: ../../library/csv.rst:608 +#: ../../library/csv.rst:620 +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(f'file {filename}, line {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(f'file {filename}, line {reader.line_num}: {e}')" + +#: ../../library/csv.rst:630 msgid "" "And while the module doesn't directly support parsing strings, it can easily " "be done::" @@ -868,24 +1107,34 @@ 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:617 +#: ../../library/csv.rst:633 +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:639 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/csv.rst:618 +#: ../../library/csv.rst:640 msgid "" "If ``newline=''`` is not specified, newlines embedded inside quoted fields " -"will not be interpreted correctly, and on platforms that use ``\\r\\n`` " -"linendings on write an extra ``\\r`` will be added. It should always be " -"safe to specify ``newline=''``, since the csv module does its own (:term:" +"will not be interpreted correctly, and on platforms that use ``\\r\\n`` line " +"endings on write an extra ``\\r`` will be added. It should always be safe " +"to specify ``newline=''``, since the csv module does its own (:term:" "`universal `) newline handling." msgstr "" -"Se ``newline=''`` não for especificado, as novas linhas incorporadas nos " -"campos entre aspas não serão interpretadas corretamente, e nas plataformas " -"que usam fim de linha ``\\r\\n`` na escrita, um ``\\r`` extra será " -"adicionado. Sempre deve ser seguro especificar ``newline=''``, já que o " -"módulo csv faz seu próprio tratamento de nova linha (:term:`universal " -"`)." +"Se ``newline=''`` não for especificado, quebras de linha inseridas em campos " +"entre aspas não serão interpretadas corretamente e, em plataformas que usam " +"terminações de linha ``\\r\\n`` na gravação, um ``\\r`` extra será " +"adicionado. É sempre seguro especificar ``newline=''``, já que o módulo csv " +"faz seu próprio tratamento de quebra de linha (:term:`universal `)." #: ../../library/csv.rst:11 msgid "csv" diff --git a/library/ctypes.po b/library/ctypes.po index 470d95046..73c300e96 100644 --- a/library/ctypes.po +++ b/library/ctypes.po @@ -1,38 +1,37 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# Rafael Fontenelle , 2025 +# Marcos Moraes, 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-11-13 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Marcos Moraes, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +54,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 +66,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 +94,54 @@ 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::" -msgstr "" +"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 "" +">>> from ctypes import *\n" +">>> print(windll.kernel32)\n" +"\n" +">>> print(cdll.msvcrt)\n" +"\n" +">>> libc = cdll.msvcrt\n" +">>>" #: ../../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 +150,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 +163,62 @@ 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 "" +">>> cdll.LoadLibrary(\"libc.so.6\")\n" +"\n" +">>> libc = CDLL(\"libc.so.6\")\n" +">>> libc\n" +"\n" +">>>" #: ../../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 "" +">>> 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" +">>>" + #: ../../library/ctypes.rst:108 msgid "" "Note that win32 system dlls like ``kernel32`` and ``user32`` often export " @@ -137,6 +229,25 @@ msgid "" "following C prototype, and a macro is used to expose one of them as " "``GetModuleHandle`` depending on whether UNICODE is defined or not::" msgstr "" +"Observe que DLLs de sistema do Win32, como ``kernel32`` e ``user32``, " +"frequentemente exportam versões ANSI e UNICODE de uma função. A versão " +"UNICODE é exportada com um ``W`` anexado ao nome, enquanto a versão ANSI é " +"exportada com um ``A`` anexado ao nome. A função ``GetModuleHandle`` do " +"Win32, que retorna um *identificador de módulo* para um determinado nome de " +"módulo, tem o seguinte protótipo em C, e uma macro é usada para expor um " +"deles como ``GetModuleHandle``, dependendo se UNICODE está definido ou não:" + +#: ../../library/ctypes.rst:116 +msgid "" +"/* ANSI version */\n" +"HMODULE GetModuleHandleA(LPCSTR lpModuleName);\n" +"/* UNICODE version */\n" +"HMODULE GetModuleHandleW(LPCWSTR lpModuleName);" +msgstr "" +"/* versão ANSI */\n" +"HMODULE GetModuleHandleA(LPCSTR lpModuleName);\n" +"/* versão UNICODE */\n" +"HMODULE GetModuleHandleW(LPCWSTR lpModuleName);" #: ../../library/ctypes.rst:121 msgid "" @@ -144,6 +255,9 @@ msgid "" "version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW`` " "explicitly, and then call it with bytes or string objects respectively." msgstr "" +"*windll* não tenta selecionar um deles magicamente, você deve acessar a " +"versão necessária especificando ``GetModuleHandleA`` ou ``GetModuleHandleW`` " +"explicitamente e então chamá-lo com objetos bytes ou string, respectivamente." #: ../../library/ctypes.rst:125 msgid "" @@ -151,6 +265,19 @@ msgid "" "identifiers, like ``\"??2@YAPAXI@Z\"``. In this case you have to use :func:" "`getattr` to retrieve the function::" msgstr "" +"Às vezes, DLLs exportam funções com nomes que não são identificadores Python " +"válidos, como ``\"??2@YAPAXI@Z\"``. Nesse caso, você precisa usar :func:" +"`getattr` para recuperar a função::" + +#: ../../library/ctypes.rst:129 +msgid "" +">>> getattr(cdll.msvcrt, \"??2@YAPAXI@Z\")\n" +"<_FuncPtr object at 0x...>\n" +">>>" +msgstr "" +">>> getattr(cdll.msvcrt, \"??2@YAPAXI@Z\")\n" +"<_FuncPtr object at 0x...>\n" +">>>" #: ../../library/ctypes.rst:133 msgid "" @@ -158,10 +285,35 @@ msgid "" "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 "" +">>> 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" +">>>" #: ../../library/ctypes.rst:150 msgid "Calling functions" -msgstr "" +msgstr "Chamando funções" #: ../../library/ctypes.rst:152 msgid "" @@ -169,6 +321,17 @@ msgid "" "uses the ``rand()`` function, which takes no arguments and returns a pseudo-" "random integer::" msgstr "" +"Você pode chamar essas funções como qualquer outro chamável do Python. Este " +"exemplo usa a função ``rand()``, que não aceita argumentos e retorna um " +"inteiro pseudoaleatório:" + +#: ../../library/ctypes.rst:155 +msgid "" +">>> print(libc.rand())\n" +"1804289383" +msgstr "" +">>> print(libc.rand())\n" +"1804289383" #: ../../library/ctypes.rst:158 msgid "" @@ -176,18 +339,65 @@ msgid "" "a win32 module handle (passing ``None`` as single argument to call it with a " "``NULL`` pointer)::" msgstr "" +"No Windows, você pode chamar a função ``GetModuleHandleA()``, que retorna um " +"identificador de módulo win32 (passando ``None`` como único argumento para " +"chamá-lo com um ponteiro ``NULL``)::" + +#: ../../library/ctypes.rst:161 +msgid "" +">>> print(hex(windll.kernel32.GetModuleHandleA(None)))\n" +"0x1d000000\n" +">>>" +msgstr "" +">>> print(hex(windll.kernel32.GetModuleHandleA(None)))\n" +"0x1d000000\n" +">>>" #: ../../library/ctypes.rst:165 msgid "" ":exc:`ValueError` is raised when you call an ``stdcall`` function with the " "``cdecl`` calling convention, or vice versa::" msgstr "" +":exc:`ValueError` é gerado quando você chama uma função ``stdcall`` com a " +"convenção de chamada ``cdecl``, ou vice-versa::" + +#: ../../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 "" +">>> 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" +">>>" #: ../../library/ctypes.rst:180 msgid "" "To find out the correct calling convention you have to look into the C " "header file or the documentation for the function you want to call." msgstr "" +"Para descobrir a convenção de chamada correta, você precisa consultar o " +"arquivo de cabeçalho C ou a documentação da função que deseja chamar." #: ../../library/ctypes.rst:183 msgid "" @@ -195,6 +405,23 @@ msgid "" "prevent crashes from general protection faults when functions are called " "with invalid argument values::" msgstr "" +"No Windows, :mod:`ctypes` usa o tratamento de exceções estruturado do win32 " +"para evitar travamentos devido a falhas gerais de proteção quando funções " +"são chamadas com valores de argumentos inválidos::" + +#: ../../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 "" +">>> windll.kernel32.GetModuleHandleA(32)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"OSError: exception: access violation reading 0x00000020\n" +">>>" #: ../../library/ctypes.rst:193 msgid "" @@ -203,6 +430,10 @@ msgid "" "debugging crashes (e.g. from segmentation faults produced by erroneous C " "library calls)." msgstr "" +"No entanto, existem maneiras suficientes de travar o Python com :mod:" +"`ctypes`, então você deve ter cuidado de qualquer maneira. O módulo :mod:" +"`faulthandler` pode ser útil na depuração de travamentos (por exemplo, de " +"falhas de segmentação produzidas por chamadas errôneas da biblioteca C)." #: ../../library/ctypes.rst:198 msgid "" @@ -214,20 +445,31 @@ msgid "" "platform's default C :c:expr:`int` type, their value is masked to fit into " "the C type." msgstr "" +"``None``, inteiros, objetos bytes e strings (unicode) são os únicos objetos " +"nativos do Python que podem ser usados diretamente como parâmetros nessas " +"chamadas de função. ``None`` é passado como um ponteiro ``NULL`` em C, " +"objetos bytes e strings são passados como ponteiros para o bloco de memória " +"que contém seus dados (:c:expr:`char *` ou :c:expr:`wchar_t *`). Inteiros em " +"Python são passados como o tipo padrão da plataforma em C :c:expr:`int`, e " +"seu valor é mascarado para se encaixar no tipo em C." #: ../../library/ctypes.rst:205 msgid "" "Before we move on calling functions with other parameter types, we have to " "learn more about :mod:`ctypes` data types." msgstr "" +"Antes de prosseguirmos com a chamada de funções com outros tipos de " +"parâmetros, precisamos aprender mais sobre os tipos de dados :mod:`ctypes`." -#: ../../library/ctypes.rst:212 ../../library/ctypes.rst:2203 +#: ../../library/ctypes.rst:212 ../../library/ctypes.rst:2278 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:" msgstr "" +":mod:`ctypes` define uma série de tipos de dados primitivos compatíveis com " +"C:" #: ../../library/ctypes.rst:217 msgid "ctypes type" @@ -235,11 +477,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`" @@ -286,8 +528,12 @@ msgstr ":class:`c_byte`" #: ../../library/ctypes.rst:233 ../../library/ctypes.rst:235 #: ../../library/ctypes.rst:237 ../../library/ctypes.rst:239 #: ../../library/ctypes.rst:241 ../../library/ctypes.rst:243 -#: ../../library/ctypes.rst:246 ../../library/ctypes.rst:248 -#: ../../library/ctypes.rst:251 +#: ../../library/ctypes.rst:245 ../../library/ctypes.rst:247 +#: ../../library/ctypes.rst:249 ../../library/ctypes.rst:251 +#: ../../library/ctypes.rst:253 ../../library/ctypes.rst:255 +#: ../../library/ctypes.rst:257 ../../library/ctypes.rst:259 +#: ../../library/ctypes.rst:262 ../../library/ctypes.rst:264 +#: ../../library/ctypes.rst:267 msgid "int" msgstr "int" @@ -324,158 +570,302 @@ msgid ":c:expr:`int`" msgstr ":c:expr:`int`" #: ../../library/ctypes.rst:235 +msgid ":class:`c_int8`" +msgstr ":class:`c_int8`" + +#: ../../library/ctypes.rst:235 +msgid ":c:type:`int8_t`" +msgstr ":c:type:`int8_t`" + +#: ../../library/ctypes.rst:237 +msgid ":class:`c_int16`" +msgstr ":class:`c_int16`" + +#: ../../library/ctypes.rst:237 +msgid ":c:type:`int16_t`" +msgstr ":c:type:`int16_t`" + +#: ../../library/ctypes.rst:239 +msgid ":class:`c_int32`" +msgstr ":class:`c_int32`" + +#: ../../library/ctypes.rst:239 +msgid ":c:type:`int32_t`" +msgstr ":c:type:`int32_t`" + +#: ../../library/ctypes.rst:241 +msgid ":class:`c_int64`" +msgstr ":class:`c_int64`" + +#: ../../library/ctypes.rst:241 +msgid ":c:type:`int64_t`" +msgstr ":c:type:`int64_t`" + +#: ../../library/ctypes.rst:243 msgid ":class:`c_uint`" msgstr ":class:`c_uint`" -#: ../../library/ctypes.rst:235 +#: ../../library/ctypes.rst:243 msgid ":c:expr:`unsigned int`" msgstr ":c:expr:`unsigned int`" -#: ../../library/ctypes.rst:237 +#: ../../library/ctypes.rst:245 +msgid ":class:`c_uint8`" +msgstr ":class:`c_uint8`" + +#: ../../library/ctypes.rst:245 +msgid ":c:type:`uint8_t`" +msgstr ":c:type:`uint8_t`" + +#: ../../library/ctypes.rst:247 +msgid ":class:`c_uint16`" +msgstr ":class:`c_uint16`" + +#: ../../library/ctypes.rst:247 +msgid ":c:type:`uint16_t`" +msgstr ":c:type:`uint16_t`" + +#: ../../library/ctypes.rst:249 +msgid ":class:`c_uint32`" +msgstr ":class:`c_uint32`" + +#: ../../library/ctypes.rst:249 +msgid ":c:type:`uint32_t`" +msgstr ":c:type:`uint32_t`" + +#: ../../library/ctypes.rst:251 +msgid ":class:`c_uint64`" +msgstr ":class:`c_uint64`" + +#: ../../library/ctypes.rst:251 +msgid ":c:type:`uint64_t`" +msgstr ":c:type:`uint64_t`" + +#: ../../library/ctypes.rst:253 msgid ":class:`c_long`" msgstr ":class:`c_long`" -#: ../../library/ctypes.rst:237 +#: ../../library/ctypes.rst:253 msgid ":c:expr:`long`" msgstr ":c:expr:`long`" -#: ../../library/ctypes.rst:239 +#: ../../library/ctypes.rst:255 msgid ":class:`c_ulong`" msgstr ":class:`c_ulong`" -#: ../../library/ctypes.rst:239 +#: ../../library/ctypes.rst:255 msgid ":c:expr:`unsigned long`" msgstr ":c:expr:`unsigned long`" -#: ../../library/ctypes.rst:241 +#: ../../library/ctypes.rst:257 msgid ":class:`c_longlong`" msgstr ":class:`c_longlong`" -#: ../../library/ctypes.rst:241 +#: ../../library/ctypes.rst:257 msgid ":c:expr:`__int64` or :c:expr:`long long`" -msgstr "" +msgstr ":c:expr:`__int64` ou :c:expr:`long long`" -#: ../../library/ctypes.rst:243 +#: ../../library/ctypes.rst:259 msgid ":class:`c_ulonglong`" msgstr ":class:`c_ulonglong`" -#: ../../library/ctypes.rst:243 +#: ../../library/ctypes.rst:259 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 +#: ../../library/ctypes.rst:262 msgid ":class:`c_size_t`" msgstr ":class:`c_size_t`" -#: ../../library/ctypes.rst:246 +#: ../../library/ctypes.rst:262 msgid ":c:type:`size_t`" msgstr ":c:type:`size_t`" -#: ../../library/ctypes.rst:248 +#: ../../library/ctypes.rst:264 msgid ":class:`c_ssize_t`" msgstr ":class:`c_ssize_t`" -#: ../../library/ctypes.rst:248 +#: ../../library/ctypes.rst:264 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 +#: ../../library/ctypes.rst:267 msgid ":class:`c_time_t`" msgstr ":class:`c_time_t`" -#: ../../library/ctypes.rst:251 +#: ../../library/ctypes.rst:267 msgid ":c:type:`time_t`" msgstr ":c:type:`time_t`" -#: ../../library/ctypes.rst:253 +#: ../../library/ctypes.rst:269 msgid ":class:`c_float`" msgstr ":class:`c_float`" -#: ../../library/ctypes.rst:253 +#: ../../library/ctypes.rst:269 msgid ":c:expr:`float`" msgstr ":c:expr:`float`" -#: ../../library/ctypes.rst:253 ../../library/ctypes.rst:255 -#: ../../library/ctypes.rst:257 +#: ../../library/ctypes.rst:269 ../../library/ctypes.rst:271 +#: ../../library/ctypes.rst:273 msgid "float" -msgstr "float" +msgstr "ponto flutuante" -#: ../../library/ctypes.rst:255 +#: ../../library/ctypes.rst:271 msgid ":class:`c_double`" msgstr ":class:`c_double`" -#: ../../library/ctypes.rst:255 +#: ../../library/ctypes.rst:271 msgid ":c:expr:`double`" msgstr ":c:expr:`double`" -#: ../../library/ctypes.rst:257 +#: ../../library/ctypes.rst:273 msgid ":class:`c_longdouble`" msgstr ":class:`c_longdouble`" -#: ../../library/ctypes.rst:257 +#: ../../library/ctypes.rst:273 msgid ":c:expr:`long double`" msgstr ":c:expr:`long double`" -#: ../../library/ctypes.rst:259 +#: ../../library/ctypes.rst:275 msgid ":class:`c_char_p`" msgstr ":class:`c_char_p`" -#: ../../library/ctypes.rst:259 +#: ../../library/ctypes.rst:275 msgid ":c:expr:`char *` (NUL terminated)" -msgstr "" +msgstr ":c:expr:`char *` (finalizado com NUL)" -#: ../../library/ctypes.rst:259 +#: ../../library/ctypes.rst:275 msgid "bytes object or ``None``" -msgstr "bytes object ou ``None``" +msgstr "objeto bytes ou ``None``" -#: ../../library/ctypes.rst:261 +#: ../../library/ctypes.rst:277 msgid ":class:`c_wchar_p`" msgstr ":class:`c_wchar_p`" -#: ../../library/ctypes.rst:261 +#: ../../library/ctypes.rst:277 msgid ":c:expr:`wchar_t *` (NUL terminated)" -msgstr "" +msgstr ":c:expr:`wchar_t *` (finalizado com NUL)" -#: ../../library/ctypes.rst:261 +#: ../../library/ctypes.rst:277 msgid "string or ``None``" msgstr "String ou ``None``" -#: ../../library/ctypes.rst:263 +#: ../../library/ctypes.rst:279 msgid ":class:`c_void_p`" msgstr ":class:`c_void_p`" -#: ../../library/ctypes.rst:263 +#: ../../library/ctypes.rst:279 msgid ":c:expr:`void *`" msgstr ":c:expr:`void *`" -#: ../../library/ctypes.rst:263 +#: ../../library/ctypes.rst:279 msgid "int or ``None``" msgstr "int ou ``None``" -#: ../../library/ctypes.rst:267 +#: ../../library/ctypes.rst:283 msgid "The constructor accepts any object with a truth value." -msgstr "" +msgstr "O construtor aceita qualquer objeto com um valor verdade." -#: ../../library/ctypes.rst:269 +#: ../../library/ctypes.rst:285 msgid "" "All these types can be created by calling them with an optional initializer " "of the correct type and value::" msgstr "" +"Todos esses tipos podem ser criados chamando-os com um inicializador " +"opcional do tipo e valor corretos::" -#: ../../library/ctypes.rst:280 +#: ../../library/ctypes.rst:288 msgid "" -"Since these types are mutable, their value can also be changed afterwards::" +">>> 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 "" +">>> c_int()\n" +"c_long(0)\n" +">>> c_wchar_p(\"Olá, mundo\")\n" +"c_wchar_p(139878537078816)\n" +">>> c_ushort(-3)\n" +"c_ushort(65533)\n" +">>>" -#: ../../library/ctypes.rst:292 +#: ../../library/ctypes.rst:296 +msgid "" +"Since these types are mutable, their value can also be changed afterwards::" +msgstr "" +"Como esses tipos são mutáveis, seus valores também podem ser alterados " +"posteriormente::" + +#: ../../library/ctypes.rst:298 +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 "" +">>> 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" +">>>" + +#: ../../library/ctypes.rst:308 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)::" -msgstr "" - -#: ../../library/ctypes.rst:312 +"Python string objects are immutable)::" +msgstr "" +"Atribuir um novo valor a instâncias dos tipos de ponteiro :class:" +"`c_char_p`, :class:`c_wchar_p` e :class:`c_void_p` altera o *local de " +"memória* para o qual eles apontam, *não o conteúdo* do bloco de memória " +"(claro que não, porque objetos string do Python são imutáveis)::" + +#: ../../library/ctypes.rst:313 +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 "" +">>> s = \"Olá, mundo\"\n" +">>> c_s = c_wchar_p(s)\n" +">>> print(c_s)\n" +"c_wchar_p(139878542513936)\n" +">>> print(c_s.value)\n" +"Olá, mundo\n" +">>> c_s.value = \"Opa, beleza?\"\n" +">>> print(c_s) # o local da memória foi alterado\n" +"c_wchar_p(139878536944240)\n" +">>> print(c_s.value)\n" +"Opa, beleza?\n" +">>> print(s) # primeiro objeto está inalterado\n" +"Olá, mundo\n" +">>>" + +#: ../../library/ctypes.rst:328 msgid "" "You should be careful, however, not to pass them to functions expecting " "pointers to mutable memory. If you need mutable memory blocks, ctypes has a :" @@ -484,38 +874,123 @@ msgid "" "``raw`` property; if you want to access it as NUL terminated string, use the " "``value`` property::" msgstr "" - -#: ../../library/ctypes.rst:336 +"No entanto, tome cuidado para não passá-los para funções que esperam " +"ponteiros para memória mutável. Se precisar de blocos de memória mutáveis, o " +"ctypes possui uma função :func:`create_string_buffer` que os cria de várias " +"maneiras. O conteúdo do bloco de memória atual pode ser acessado (ou " +"alterado) com a propriedade ``raw``; se quiser acessá-lo como uma string " +"terminada em NUL, use a propriedade ``value``:" + +#: ../../library/ctypes.rst:335 +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 "" +">>> from ctypes import *\n" +">>> p = create_string_buffer(3) # cria um buffer de 3 bytes, " +"inicializado para NUL bytes\n" +">>> print(sizeof(p), repr(p.raw))\n" +"3 b'\\x00\\x00\\x00'\n" +">>> p = create_string_buffer(b\"Opa\") # cria um buffer contendo uma " +"string terminando com NUL\n" +">>> print(sizeof(p), repr(p.raw))\n" +"4 b'Opa\\x00'\n" +">>> print(repr(p.value))\n" +"b'Opa'\n" +">>> p = create_string_buffer(b\"Oi\", 10) # cria um buffer de 10 bytes\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Oi\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n" +">>> p.value = b\"Oi\"\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Oi\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n" +">>>" + +#: ../../library/ctypes.rst:352 msgid "" "The :func:`create_string_buffer` function replaces the old :func:`!c_buffer` " "function (which is still available as an alias). To create a mutable memory " "block containing unicode characters of the C type :c:type:`wchar_t`, use " "the :func:`create_unicode_buffer` function." msgstr "" +"A função :func:`create_string_buffer` substitui a antiga função :func:`!" +"c_buffer` (que ainda está disponível como um apelido). Para criar um bloco " +"de memória mutável contendo caracteres Unicode do tipo C :c:type:`wchar_t`, " +"use a função :func:`create_unicode_buffer`." -#: ../../library/ctypes.rst:345 +#: ../../library/ctypes.rst:361 msgid "Calling functions, continued" -msgstr "Invocação de Funções, continuação" +msgstr "Chamando funções, continuação" -#: ../../library/ctypes.rst:347 +#: ../../library/ctypes.rst:363 msgid "" "Note that printf prints to the real standard output channel, *not* to :data:" "`sys.stdout`, so these examples will only work at the console prompt, not " "from within *IDLE* or *PythonWin*::" msgstr "" +"Observe que printf imprime no canal de saída padrão real, *não* em :data:" +"`sys.stdout`, então esses exemplos só funcionarão no prompt do console, não " +"de dentro do *IDLE* ou *PythonWin*::" #: ../../library/ctypes.rst:367 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:383 +msgid "" "As has been mentioned before, all Python types except integers, strings, and " "bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, " "so that they can be converted to the required C data type::" msgstr "" +"Como mencionado anteriormente, todos os tipos do Python, exceto inteiros, " +"strings e objetos bytes, precisam ser encapsulados em seu tipo " +"correspondente de :mod:`ctypes`, para que possam ser convertidos para o tipo " +"de dado C necessário::" -#: ../../library/ctypes.rst:379 -msgid "Calling variadic functions" +#: ../../library/ctypes.rst:387 +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:381 +#: ../../library/ctypes.rst:395 +msgid "Calling variadic functions" +msgstr "Chamando funções variadas" + +#: ../../library/ctypes.rst:397 msgid "" "On a lot of platforms calling variadic functions through ctypes is exactly " "the same as calling functions with a fixed number of parameters. On some " @@ -523,24 +998,38 @@ msgid "" "convention for variadic functions is different than that for regular " "functions." msgstr "" +"Em muitas plataformas chamar funções variádicas por meio do ctypes é " +"exatamente o mesmo que chamar funções com um número fixo de parâmetros. Em " +"algumas plataformas, em particular no ARM64 para plataformas Apple, a " +"convenção de chamada para funções variádicas é diferente daquela usada para " +"funções regulares." -#: ../../library/ctypes.rst:386 +#: ../../library/ctypes.rst:402 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 "" +"Nessas plataformas é necessário especificar o atributo :attr:`~_CFuncPtr." +"argtypes` para os argumentos de função regulares (não variádicos):" -#: ../../library/ctypes.rst:393 +#: ../../library/ctypes.rst:405 +msgid "libc.printf.argtypes = [ctypes.c_char_p]" +msgstr "" + +#: ../../library/ctypes.rst:409 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 "" +"Já que especificar o atributo não impede a portabilidade, recomenda-se " +"sempre especificar o :attr:`~_CFuncPtr.argtypes` para todas as funções " +"variádicas." -#: ../../library/ctypes.rst:400 +#: ../../library/ctypes.rst:416 msgid "Calling functions with your own custom data types" -msgstr "" +msgstr "Chamando funções com seus próprios tipos de dados personalizados" -#: ../../library/ctypes.rst:402 +#: ../../library/ctypes.rst:418 msgid "" "You can also customize :mod:`ctypes` argument conversion to allow instances " "of your own classes be used as function arguments. :mod:`ctypes` looks for " @@ -548,45 +1037,100 @@ msgid "" "The attribute must be an integer, string, bytes, a :mod:`ctypes` instance, " "or an object with an :attr:`!_as_parameter_` attribute::" msgstr "" +"Você também pode personalizar a conversão de argumentos do :mod:`ctypes` " +"para permitir que instâncias das suas próprias classes sejam usadas como " +"argumento de função. O :mod:`ctypes` procura um atributo :attr:`!" +"_as_parameter_` e o utiliza como o argumento da função. O atributo deve ser " +"um inteiro, string, bytes, uma instância de :mod:`ctypes`, ou um objeto com " +"um atributo :attr:`!_as_parameter_`::" -#: ../../library/ctypes.rst:418 +#: ../../library/ctypes.rst:424 +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:434 msgid "" "If you don't want to store the instance's data in the :attr:`!" "_as_parameter_` instance variable, you could define a :class:`property` " "which makes the attribute available on request." msgstr "" +"Se você não quiser armazenar os dados da instância na variável de instância :" +"attr:`!_as_parameter_`, você pode definir uma :class:`property` que " +"disponibilize o atributo mediante solicitação." -#: ../../library/ctypes.rst:426 +#: ../../library/ctypes.rst:442 msgid "Specifying the required argument types (function prototypes)" msgstr "" +"Especificando os tipos de argumentos necessários (protótipos de função)" -#: ../../library/ctypes.rst:428 +#: ../../library/ctypes.rst:444 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 "" +"É possível especificar os tipos de argumentos necessários de funções " +"exportadas de DLLs definindo o atributo :attr:`~_CFuncPtr.argtypes`." -#: ../../library/ctypes.rst:431 +#: ../../library/ctypes.rst:447 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 "" +":attr:`~_CFuncPtr.argtypes` deve ser uma sequência de tipos de dados C (a " +"função :func:`!printf` provavelmente não é um bom exemplo nesse caso, pois " +"ela aceita um número variável e diferentes tipos de parâmetros dependendo da " +"string de formato; por outro lado, ela é bastante útil para experimentar " +"esse recurso)::" -#: ../../library/ctypes.rst:442 +#: ../../library/ctypes.rst:452 +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:458 msgid "" "Specifying a format protects against incompatible argument types (just as a " "prototype for a C function), and tries to convert the arguments to valid " "types::" msgstr "" +"Especificar um formato protege contra tipos de argumentos incompatíveis " +"(assim como um protótipo para uma função em C), e tenta converter os " +"argumentos para tipos válidos::" -#: ../../library/ctypes.rst:454 +#: ../../library/ctypes.rst:461 +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:470 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:`!" @@ -595,86 +1139,190 @@ msgid "" "bytes, a :mod:`ctypes` instance, or an object with an :attr:`!" "_as_parameter_` attribute." msgstr "" - -#: ../../library/ctypes.rst:468 +"Se você definiu suas próprias classes que serão passadas em chamadas de " +"função, é necessário implementar um método de classe :meth:`~_CData." +"from_param` para que elas possam ser usadas na sequência :attr:`~_CFuncPtr." +"argtypes`. O método de classe :meth:`~_CData.from_param` recebe o objeto " +"Python passado para a chamada de função; ele deve realizar um typecheck ou o " +"que for necessário para garantir que esse objeto seja aceitável, e então " +"retornar o próprio objeto, seu atributo :attr:`!_as_parameter_` ou qualquer " +"valor que você queira passar como argumento da função C nesse caso. " +"Novamente, o resultado deve ser um inteiro, string, bytes, uma instância de :" +"mod:`ctypes` ou um objeto com um atributo :attr:`!_as_parameter_`." + +#: ../../library/ctypes.rst:484 msgid "Return types" msgstr "Tipos de Retorno" -#: ../../library/ctypes.rst:478 +#: ../../library/ctypes.rst:494 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 "" +"Por padrão, as funções são presumidas como retornando o tipo C :c:expr:" +"`int`. Outros retornos podem ser especificados definindo o atributo :attr:" +"`~_CFuncPtr.restype` do objeto função." -#: ../../library/ctypes.rst:482 +#: ../../library/ctypes.rst:498 msgid "" "The C prototype of :c:func:`time` is ``time_t time(time_t *)``. Because :c:" "type:`time_t` might be of a different type than the default return type :c:" "expr:`int`, you should specify the :attr:`!restype` attribute::" msgstr "" +"O protótipo C de :c:func:`time` é ``time_t time(time_t *)``. Porque :c:type:" +"`time_t` pode ser de um tipo diferente do tipo de retorno padrão :c:expr:" +"`int`, você deve especificar o atributo :attr:`!restype`." -#: ../../library/ctypes.rst:488 -msgid "The argument types can be specified using :attr:`~_FuncPtr.argtypes`::" +#: ../../library/ctypes.rst:502 +msgid ">>> libc.time.restype = c_time_t" msgstr "" -#: ../../library/ctypes.rst:492 +#: ../../library/ctypes.rst:504 +msgid "The argument types can be specified using :attr:`~_CFuncPtr.argtypes`::" +msgstr "" +"Os tipos de argumentos podem ser especificados usando :attr:`~_CFuncPtr." +"argtypes`::" + +#: ../../library/ctypes.rst:506 +msgid ">>> libc.time.argtypes = (POINTER(c_time_t),)" +msgstr "" + +#: ../../library/ctypes.rst:508 msgid "" "To call the function with a ``NULL`` pointer as first argument, use " "``None``::" msgstr "" +"Para chamar uma função com um ponteiro ``NULL`` como primeiro argumento, use " +"``None``::" + +#: ../../library/ctypes.rst:510 +msgid "" +">>> print(libc.time(None))\n" +"1150640792" +msgstr "" -#: ../../library/ctypes.rst:497 +#: ../../library/ctypes.rst:513 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 "" +"Aqui está um exemplo mais avançado, ele usa a função :func:`!strchr`, que " +"espera um ponteiro de string e um char, e retorna um ponteiro para uma " +"string::" -#: ../../library/ctypes.rst:510 +#: ../../library/ctypes.rst:516 +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:526 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:529 +#: ../../library/ctypes.rst:530 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::" +">>> 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:552 +#: ../../library/ctypes.rst:545 +msgid "" +"You can also use a callable Python object (a function or a class for " +"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 "" +"Você também pode usar um objeto Python chamável (uma função ou uma classe, " +"por exemplo) como o atributo :attr:`~_CFuncPtr.restype`, se a função externa " +"retornar um inteiro. O objeto chamável será chamado com o *inteiro* que a " +"função C retorna, e o resultado desta chamada será usado como o resultado da " +"sua chamada de função. Isso é útil para verificar valores de retorno de erro " +"e levantar uma exceção automaticamente::" + +#: ../../library/ctypes.rst:551 +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:568 msgid "" "``WinError`` is a function which will call Windows ``FormatMessage()`` api " "to get the string representation of an error code, and *returns* an " "exception. ``WinError`` takes an optional error code parameter, if no one is " "used, it calls :func:`GetLastError` to retrieve it." msgstr "" +"``WinError`` é uma função que chamará a API ``FormatMessage()`` do Windows " +"para obter a representação em string de um código de erro, e *retorna* uma " +"exceção. ``WinError`` aceita um parâmetro de código de erro opcional, se " +"nenhum for usado, ela chama :func:`GetLastError` para recuperá-lo." -#: ../../library/ctypes.rst:557 +#: ../../library/ctypes.rst:573 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 "" +"Por favor, repare que um mecanismo de checagem de erro muito mais poderoso " +"está disponível através do atributo :attr:`~_CFuncPtr.errcheck`; consulte o " +"manual de referência para mais detalhes." -#: ../../library/ctypes.rst:565 +#: ../../library/ctypes.rst:581 msgid "Passing pointers (or: passing parameters by reference)" -msgstr "" +msgstr "Passando ponteiros (ou: passando parâmetros por referência)" -#: ../../library/ctypes.rst:567 +#: ../../library/ctypes.rst:583 msgid "" "Sometimes a C api function expects a *pointer* to a data type as parameter, " "probably to write into the corresponding location, or if the data is too " "large to be passed by value. This is also known as *passing parameters by " "reference*." msgstr "" +"Às vezes, uma função da API C espera um *ponteiro* para um tipo de dado como " +"parâmetro, provavelmente para escrever no local correspondente, ou se os " +"dados forem muito grandes para serem passados por valor. Isso também é " +"conhecido como *passar parâmetros por referência*." -#: ../../library/ctypes.rst:571 +#: ../../library/ctypes.rst:587 msgid "" ":mod:`ctypes` exports the :func:`byref` function which is used to pass " "parameters by reference. The same effect can be achieved with the :func:" @@ -682,12 +1330,32 @@ msgid "" "constructs a real pointer object, so it is faster to use :func:`byref` if " "you don't need the pointer object in Python itself::" msgstr "" +"O :mod:`ctypes` exporta a função :func:`byref` que é usada para passar " +"parâmetros por referência. O mesmo efeito pode ser alcançado com a função :" +"func:`pointer`, embora :func:`pointer` faça muito mais trabalho, já que ela " +"constrói um objeto ponteiro real, então é mais rápido usar :func:`byref` se " +"você não precisar do objeto ponteiro no próprio Python::" #: ../../library/ctypes.rst:593 -msgid "Structures and unions" +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:595 +#: ../../library/ctypes.rst:609 +msgid "Structures and unions" +msgstr "Estruturas e uniões" + +#: ../../library/ctypes.rst:611 msgid "" "Structures and unions must derive from the :class:`Structure` and :class:" "`Union` base classes which are defined in the :mod:`ctypes` module. Each " @@ -695,57 +1363,128 @@ msgid "" "_fields_` must be a list of *2-tuples*, containing a *field name* and a " "*field type*." msgstr "" +"Estruturas e uniões devem derivar das classes base :class:`Structure` e :" +"class:`Union` que são definidas no módulo :mod:`ctypes`. Cada subclasse deve " +"definir um atributo :attr:`~Structure._fields_`. :attr:`!_fields_` deve ser " +"uma lista de *2-tuplas*, contendo um *nome de campo* e um *tipo de campo*." -#: ../../library/ctypes.rst:600 +#: ../../library/ctypes.rst:616 msgid "" "The field type must be a :mod:`ctypes` type like :class:`c_int`, or any " "other derived :mod:`ctypes` type: structure, union, array, pointer." msgstr "" +"O tipo do campo deve ser um tipo :mod:`ctypes` como :class:`c_int`, ou " +"qualquer outro tipo :mod:`ctypes` derivado: estrutura, união, vetor, " +"ponteiro." -#: ../../library/ctypes.rst:603 +#: ../../library/ctypes.rst:619 msgid "" "Here is a simple example of a POINT structure, which contains two integers " "named *x* and *y*, and also shows how to initialize a structure in the " "constructor::" msgstr "" +"Aqui está um exemplo simples de uma estrutura POINT, que contém dois " +"inteiros nomeados *x* e *y*, e também mostra como inicializar uma estrutura " +"no construtor::" -#: ../../library/ctypes.rst:623 +#: ../../library/ctypes.rst:622 +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:639 msgid "" "You can, however, build much more complicated structures. A structure can " "itself contain other structures by using a structure as a field type." msgstr "" +"Você pode, no entanto, construir estruturas muito mais complicadas. Uma " +"estrutura pode conter outras estruturas, usando uma estrutura como um tipo " +"de campo." -#: ../../library/ctypes.rst:626 +#: ../../library/ctypes.rst:642 msgid "" "Here is a RECT structure which contains two POINTs named *upperleft* and " "*lowerright*::" msgstr "" +"Aqui está uma estrutura RECT que contém dois POINTs nomeados *upperleft* e " +"*lowerright*::" + +#: ../../library/ctypes.rst:645 +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 +#: ../../library/ctypes.rst:656 msgid "" "Nested structures can also be initialized in the constructor in several " "ways::" msgstr "" +"Estruturas aninhadas também podem ser inicializadas no construtor de várias " +"maneiras::" -#: ../../library/ctypes.rst:645 +#: ../../library/ctypes.rst:658 +msgid "" +">>> r = RECT(POINT(1, 2), POINT(3, 4))\n" +">>> r = RECT((1, 2), (3, 4))" +msgstr "" + +#: ../../library/ctypes.rst:661 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:659 +#: ../../library/ctypes.rst:664 +msgid "" +">>> print(POINT.x)\n" +"\n" +">>> print(POINT.y)\n" +"\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:675 msgid "" ":mod:`ctypes` does not support passing unions or structures with bit-fields " "to functions by value. While this may work on 32-bit x86, it's not " "guaranteed by the library to work in the general case. Unions and " "structures with bit-fields should always be passed to functions by pointer." msgstr "" +"O :mod:`ctypes` não suporta passar uniões ou estruturas com campos de bits " +"(bit-fields) para funções por valor. Embora isso possa funcionar em x86 de " +"32 bits, não é garantido pela biblioteca que funcione no caso geral. Uniões " +"e estruturas com campos de bits devem sempre ser passadas para funções por " +"ponteiro." -#: ../../library/ctypes.rst:665 +#: ../../library/ctypes.rst:681 msgid "Structure/union alignment and byte order" msgstr "" -#: ../../library/ctypes.rst:667 +#: ../../library/ctypes.rst:683 msgid "" "By default, Structure and Union fields are aligned in the same way the C " "compiler does it. It is possible to override this behavior by specifying a :" @@ -754,11 +1493,11 @@ 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 "" -#: ../../library/ctypes.rst:677 +#: ../../library/ctypes.rst:693 msgid "" ":mod:`ctypes` uses the native byte order for Structures and Unions. To " "build structures with non-native byte order, you can use one of the :class:" @@ -766,92 +1505,220 @@ msgid "" "`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These " "classes cannot contain pointer fields." msgstr "" +":mod:`ctypes` usa a ordem de bytes nativa para Estruturas e Uniões. Para " +"construir estruturas com ordem de bytes não nativa, você pode usar classes " +"base :class:`BigEndianStructure`, :class:`LittleEndianStructure`, :class:" +"`BigEndianUnion` e :class:`LittleEndianUnion`. Essas classes não podem " +"conter campos de ponteiros." -#: ../../library/ctypes.rst:687 +#: ../../library/ctypes.rst:703 msgid "Bit fields in structures and unions" -msgstr "" +msgstr "Campos de bit em estruturas e uniões" -#: ../../library/ctypes.rst:689 +#: ../../library/ctypes.rst:705 msgid "" "It is possible to create structures and unions containing bit fields. Bit " "fields are only possible for integer fields, the bit width is specified as " "the third item in the :attr:`~Structure._fields_` tuples::" msgstr "" +"É possível criar estruturas e uniões contendo campos de bits. Campos de bits " +"só são possíveis para campos de inteiros, a largura do bit é especificada " +"como o terceiro item nas tuplas :attr:`~Structure._fields_`::" -#: ../../library/ctypes.rst:707 +#: ../../library/ctypes.rst:709 +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:723 msgid "Arrays" msgstr "Arrays" -#: ../../library/ctypes.rst:709 +#: ../../library/ctypes.rst:725 msgid "" "Arrays are sequences, containing a fixed number of instances of the same " "type." msgstr "" +"Vetores são sequências, contendo um número fixo de instâncias do mesmo tipo." -#: ../../library/ctypes.rst:711 +#: ../../library/ctypes.rst:727 msgid "" "The recommended way to create array types is by multiplying a data type with " "a positive integer::" msgstr "" +"A maneira recomendada de criar tipos vetor é multiplicando um tipo de dado " +"por um inteiro positivo::" + +#: ../../library/ctypes.rst:730 +msgid "TenPointsArrayType = POINT * 10" +msgstr "" -#: ../../library/ctypes.rst:716 +#: ../../library/ctypes.rst:732 msgid "" "Here is an example of a somewhat artificial data type, a structure " "containing 4 POINTs among other stuff::" msgstr "" +"Aqui está um exemplo de um tipo de dado um tanto artificial, uma estrutura " +"contendo 4 POINTs entre outras coisas::" -#: ../../library/ctypes.rst:732 +#: ../../library/ctypes.rst:735 +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:748 msgid "Instances are created in the usual way, by calling the class::" +msgstr "Instâncias são criadas da maneira usual, chamando a classe::" + +#: ../../library/ctypes.rst:750 +msgid "" +"arr = TenPointsArrayType()\n" +"for pt in arr:\n" +" print(pt.x, pt.y)" msgstr "" -#: ../../library/ctypes.rst:738 +#: ../../library/ctypes.rst:754 msgid "" "The above code print a series of ``0 0`` lines, because the array contents " "is initialized to zeros." msgstr "" +"O código acima exibe uma série de linhas ``0 0``, pois o conteúdo do vetor é " +"inicializado com zeros." -#: ../../library/ctypes.rst:741 +#: ../../library/ctypes.rst:757 msgid "Initializers of the correct type can also be specified::" +msgstr "Inicializadores do tipo correto também podem ser especificados::" + +#: ../../library/ctypes.rst:759 +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 +#: ../../library/ctypes.rst:773 msgid "Pointers" msgstr "Ponteiros" -#: ../../library/ctypes.rst:759 +#: ../../library/ctypes.rst:775 msgid "" "Pointer instances are created by calling the :func:`pointer` function on a :" "mod:`ctypes` type::" msgstr "" +"Instâncias de ponteiro são criadas chamando a função :func:`pointer` em um " +"tipo :mod:`ctypes`::" -#: ../../library/ctypes.rst:767 +#: ../../library/ctypes.rst:778 +msgid "" +">>> from ctypes import *\n" +">>> i = c_int(42)\n" +">>> pi = pointer(i)\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:783 msgid "" "Pointer instances have a :attr:`~_Pointer.contents` attribute which returns " "the object to which the pointer points, the ``i`` object above::" msgstr "" +"Instâncias de ponteiros têm um atributo :attr:`~_Pointer.contents` que " +"retorna o objeto para qual o ponteiro aponta, o objeto ``i`` acima::" -#: ../../library/ctypes.rst:774 +#: ../../library/ctypes.rst:786 +msgid "" +">>> pi.contents\n" +"c_long(42)\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:790 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 "" +"Note que o :mod:`ctypes` não possui OOR (retorno de objeto original), ele " +"constrói um objeto novo e equivalente cada vez que você recupera um " +"atributo::" -#: ../../library/ctypes.rst:783 +#: ../../library/ctypes.rst:793 +msgid "" +">>> pi.contents is i\n" +"False\n" +">>> pi.contents is pi.contents\n" +"False\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:799 msgid "" "Assigning another :class:`c_int` instance to the pointer's contents " "attribute would cause the pointer to point to the memory location where this " "is stored::" msgstr "" +"Atribuir outra instância :class:`c_int` ao atributo do conteúdo do ponteiro " +"faria com que o ponteiro apontasse para o local de memória onde ela está " +"armazenada::" -#: ../../library/ctypes.rst:795 +#: ../../library/ctypes.rst:802 +msgid "" +">>> i = c_int(99)\n" +">>> pi.contents = i\n" +">>> pi.contents\n" +"c_long(99)\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:811 msgid "Pointer instances can also be indexed with integers::" +msgstr "Instâncias de ponteiro também podem ser indexadas com inteiros::" + +#: ../../library/ctypes.rst:813 +msgid "" +">>> pi[0]\n" +"99\n" +">>>" msgstr "" -#: ../../library/ctypes.rst:801 +#: ../../library/ctypes.rst:817 msgid "Assigning to an integer index changes the pointed to value::" +msgstr "Atribuir a um índice inteiro altera o valor apontado::" + +#: ../../library/ctypes.rst:819 +msgid "" +">>> print(i)\n" +"c_long(99)\n" +">>> pi[0] = 22\n" +">>> print(i)\n" +"c_long(22)\n" +">>>" msgstr "" -#: ../../library/ctypes.rst:810 +#: ../../library/ctypes.rst:826 msgid "" "It is also possible to use indexes different from 0, but you must know what " "you're doing, just as in C: You can access or change arbitrary memory " @@ -859,56 +1726,144 @@ msgid "" "a C function, and you *know* that the pointer actually points to an array " "instead of a single item." msgstr "" +"Também é possível usar índices diferentes de 0, mas você deve saber o que " +"está fazendo, assim como em C: Você pode acessar ou alterar locais " +"arbitrários da memória. Geralmente, você só usa este recurso se receber um " +"ponteiro de uma função C, e você *sabe* que o ponteiro na verdade aponta " +"para um vetor em vez de um único item." -#: ../../library/ctypes.rst:816 +#: ../../library/ctypes.rst:832 msgid "" "Behind the scenes, the :func:`pointer` function does more than simply create " "pointer instances, it has to create pointer *types* first. This is done with " "the :func:`POINTER` function, which accepts any :mod:`ctypes` type, and " "returns a new type::" msgstr "" +"Nos bastidores, a função :func:`pointer` faz mais do que simplesmente criar " +"instâncias de ponteiro, ela precisa criar *tipos* de ponteiro primeiro. Isso " +"é feito com a função :func:`POINTER`, que aceita qualquer tipo :mod:" +"`ctypes`, e retorna um novo tipo::" -#: ../../library/ctypes.rst:832 +#: ../../library/ctypes.rst:837 +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:848 msgid "" "Calling the pointer type without an argument creates a ``NULL`` pointer. " "``NULL`` pointers have a ``False`` boolean value::" msgstr "" +"Chamar o tipo ponteiro sem um argumento cria um ponteiro ``NULL``. Ponteiros " +"``NULL`` possuem o valor booleano ``False``::" -#: ../../library/ctypes.rst:840 +#: ../../library/ctypes.rst:851 +msgid "" +">>> null_ptr = POINTER(c_int)()\n" +">>> print(bool(null_ptr))\n" +"False\n" +">>>" +msgstr "" + +#: ../../library/ctypes.rst:856 msgid "" ":mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but " "dereferencing invalid non-\\ ``NULL`` pointers would crash Python)::" msgstr "" +"O :mod:`ctypes` verifica por ``NULL`` ao desreferenciar ponteiros (mas " +"desreferenciar ponteiros inválidos que não sejam ``NULL`` travaria o " +"Python)::" #: ../../library/ctypes.rst:859 +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:875 msgid "Type conversions" msgstr "Conversão de Tipos" -#: ../../library/ctypes.rst:861 +#: ../../library/ctypes.rst:877 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 " "array instances instead of pointer types. So, for ``POINTER(c_int)``, " "ctypes accepts an array of c_int::" msgstr "" - -#: ../../library/ctypes.rst:882 +"Normalmente, o ctypes faz uma verificação de tipos estrita. Isso significa " +"que, se você tiver ``POINTER(c_int)`` na lista :attr:`~_CFuncPtr.argtypes` " +"de uma função ou como o tipo de um campo membro em uma definição de " +"estrutura, apenas instâncias de exatamente o mesmo tipo são aceitas. Existem " +"algumas exceções a esta regra, onde o ctypes aceita outros objetos. Por " +"exemplo, você pode passar instâncias de vetor compatíveis em vez de tipos de " +"ponteiro. Assim, para ``POINTER(c_int)``, o ctypes aceita um vetor de c_int::" + +#: ../../library/ctypes.rst:884 +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:898 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." msgstr "" +"Além disso, se um argumento de função for explicitamente declarado como um " +"tipo ponteiro (como ``POINTER(c_int)``) em :attr:`~_CFuncPtr.argtypes`, um " +"objeto do tipo apontado (``c_int`` neste caso) pode ser passado para a " +"função. O ctypes aplicará a conversão :func:`byref` necessária neste caso " +"automaticamente." -#: ../../library/ctypes.rst:887 +#: ../../library/ctypes.rst:903 msgid "To set a POINTER type field to ``NULL``, you can assign ``None``::" msgstr "" +"Para definir um campo do tipo PONTEIRO como ``NULL``, você pode atribuir " +"``None``::" + +#: ../../library/ctypes.rst:905 +msgid "" +">>> bar.values = None\n" +">>>" +msgstr "" -#: ../../library/ctypes.rst:894 +#: ../../library/ctypes.rst:910 msgid "" "Sometimes you have instances of incompatible types. In C, you can cast one " "type into another type. :mod:`ctypes` provides a :func:`cast` function " @@ -916,12 +1871,27 @@ msgid "" "accepts ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its " "``values`` field, but not instances of other types::" msgstr "" +"Às vezes, você tem instâncias de tipos incompatíveis. Em C, você pode " +"converter um tipo em outro tipo. O :mod:`ctypes` fornece uma função :func:" +"`cast` que pode ser usada da mesma maneira. A estrutura ``Bar`` definida " +"acima aceita ponteiros ``POINTER(c_int)`` ou vetores :class:`c_int` para seu " +"campo ``values``, mas não instâncias de outros tipos::" -#: ../../library/ctypes.rst:906 -msgid "For these cases, the :func:`cast` function is handy." +#: ../../library/ctypes.rst:916 +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:908 +#: ../../library/ctypes.rst:922 +msgid "For these cases, the :func:`cast` function is handy." +msgstr "Para esses casos, a função :func:`cast` é útil." + +#: ../../library/ctypes.rst:924 msgid "" "The :func:`cast` function can be used to cast a ctypes instance into a " "pointer to a different ctypes data type. :func:`cast` takes two parameters, " @@ -929,83 +1899,190 @@ msgid "" "ctypes pointer type. It returns an instance of the second argument, which " "references the same memory block as the first argument::" msgstr "" +"A função :func:`cast` pode ser usada para converter uma instância ctypes em " +"um ponteiro para um diferente tipo de dado ctypes. :func:`cast` recebe dois " +"parâmetros, um objeto ctypes que é ou pode ser convertido para um ponteiro " +"de algum tipo, e um tipo ponteiro ctypes. Ela retorna uma instância do " +"segundo argumento, que referencia o mesmo bloco de memória que o primeiro " +"argumento::" + +#: ../../library/ctypes.rst:930 +msgid "" +">>> a = (c_byte * 4)()\n" +">>> cast(a, POINTER(c_int))\n" +"\n" +">>>" +msgstr "" -#: ../../library/ctypes.rst:919 +#: ../../library/ctypes.rst:935 msgid "" "So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` " "the structure::" msgstr "" +"Então, :func:`cast` pode ser usada para atribuir ao campo ``values`` da " +"estrutura ``Bar``::" + +#: ../../library/ctypes.rst:938 +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 +#: ../../library/ctypes.rst:948 msgid "Incomplete Types" msgstr "Tipos Incompletos" -#: ../../library/ctypes.rst:934 +#: ../../library/ctypes.rst:950 msgid "" "*Incomplete Types* are structures, unions or arrays whose members are not " "yet specified. In C, they are specified by forward declarations, which are " "defined later::" msgstr "" +"*Tipos Incompletos* são estruturas, uniões ou vetores, cujos membros ainda " +"não foram especificados. Em C, eles são especificados por declarações " +"antecipadas, que são definidas posteriormente::" -#: ../../library/ctypes.rst:945 +#: ../../library/ctypes.rst:954 +msgid "" +"struct cell; /* forward declaration */\n" +"\n" +"struct cell {\n" +" char *name;\n" +" struct cell *next;\n" +"};" +msgstr "" + +#: ../../library/ctypes.rst:961 msgid "" "The straightforward translation into ctypes code would be this, but it does " "not work::" +msgstr "A tradução direta para código ctypes seria esta, mas não funciona::" + +#: ../../library/ctypes.rst:964 +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 +#: ../../library/ctypes.rst:974 msgid "" "because the new ``class cell`` is not available in the class statement " "itself. In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:" "`~Structure._fields_` attribute later, after the class statement::" msgstr "" +"por que a nova ``class cell`` não está disponível na própria declaração da " +"classe. Em :mod:`ctypes`, podemos definir a classe ``cell`` e definir o " +"atributo :attr:`~Structure._fields_` posteriormente, após a declaração da " +"classe::" + +#: ../../library/ctypes.rst:978 +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 +#: ../../library/ctypes.rst:986 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 "" +"Vamos tentar. Criamos duas instâncias de ``cell``, e deixamos que elas " +"apontem uma para a outra, e finalmente seguimos a cadeia de ponteiros " +"algumas vezes::" -#: ../../library/ctypes.rst:991 +#: ../../library/ctypes.rst:989 +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:1007 msgid "Callback functions" msgstr "Funções Callbacks" -#: ../../library/ctypes.rst:993 +#: ../../library/ctypes.rst:1009 msgid "" ":mod:`ctypes` allows creating C callable function pointers from Python " "callables. These are sometimes called *callback functions*." msgstr "" +":mod:`ctypes` permite criar ponteiros de função C chamáveis a partir de " +"chamáveis Python. Estas são às vezes chamadas de *funções de retorno*." -#: ../../library/ctypes.rst:996 +#: ../../library/ctypes.rst:1012 msgid "" "First, you must create a class for the callback function. The class knows " "the calling convention, the return type, and the number and types of " "arguments this function will receive." msgstr "" +"Primeiro, você deve criar uma classe para função de retorno. A classe sabe a " +"convenção de chamada , o tipo de retorno, e o número e tipos de argumentos " +"que essa função irá receber." -#: ../../library/ctypes.rst:1000 +#: ../../library/ctypes.rst:1016 msgid "" "The :func:`CFUNCTYPE` factory function creates types for callback functions " "using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE` " "factory function creates types for callback functions using the ``stdcall`` " "calling convention." msgstr "" +"A função de fábrica :func:`CFUNCTYPE` cria tipos para funções de retorno " +"usando a convenção de chamada ``cdecl``. No Windows, a função de fábrica :" +"func:`WINFUNCTYPE` cria tipos para funções de retorno usando a convenção de " +"chamada ``stdcall``." -#: ../../library/ctypes.rst:1005 +#: ../../library/ctypes.rst:1021 msgid "" "Both of these factory functions are called with the result type as first " "argument, and the callback functions expected argument types as the " "remaining arguments." msgstr "" +"Ambas estas funções de fábrica são chamadas com o tipo de resultado como " +"primeiro argumento, e os tipos de argumento esperados da função de retorno " +"como os argumentos restantes." -#: ../../library/ctypes.rst:1009 +#: ../../library/ctypes.rst:1025 msgid "" "I will present an example here which uses the standard C library's :c:func:`!" "qsort` function, that is used to sort items with the help of a callback " "function. :c:func:`!qsort` will be used to sort an array of integers::" msgstr "" -#: ../../library/ctypes.rst:1019 +#: ../../library/ctypes.rst:1029 +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:1035 msgid "" ":func:`!qsort` must be called with a pointer to the data to sort, the number " "of items in the data array, the size of one item, and a pointer to the " @@ -1014,45 +2091,130 @@ msgid "" "is smaller than the second, a zero if they are equal, and a positive integer " "otherwise." msgstr "" +"A :func:`!qsort` deve ser chamada com um ponteiro para os dados a serem " +"ordenados, o número de itens no vetor de dados, o tamanho de um item, e um " +"ponteiro para a função de comparação, a função de retorno (callback). A " +"função de retorno será então chamada com dois ponteiros para itens, e ela " +"deve retornar um inteiro negativo se o primeiro item for menor que o " +"segundo, um zero se eles forem iguais, e um inteiro positivo caso contrário." -#: ../../library/ctypes.rst:1025 +#: ../../library/ctypes.rst:1041 msgid "" "So our callback function receives pointers to integers, and must return an " "integer. First we create the ``type`` for the callback function::" msgstr "" +"Então, nossa função de retorno (callback function) recebe ponteiros para " +"inteiros, e deve retornar um inteiro. Primeiro criamos o ``type`` para a " +"função de retorno::" + +#: ../../library/ctypes.rst:1044 +msgid "" +">>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n" +">>>" +msgstr "" -#: ../../library/ctypes.rst:1031 +#: ../../library/ctypes.rst:1047 msgid "" "To get started, here is a simple callback that shows the values it gets " "passed::" msgstr "" +"Para começar, aqui está uma função de retorno (callback) simples que mostra " +"os valores que lhe são passados::" -#: ../../library/ctypes.rst:1041 +#: ../../library/ctypes.rst:1050 +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:1057 msgid "The result::" msgstr "O resultado::" -#: ../../library/ctypes.rst:1051 +#: ../../library/ctypes.rst:1059 +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:1067 msgid "Now we can actually compare the two items and return a useful result::" msgstr "" +"Agora podemos realmente comparar os dois itens e retornar um resultado útil::" -#: ../../library/ctypes.rst:1066 +#: ../../library/ctypes.rst:1069 +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:1082 msgid "As we can easily check, our array is sorted now::" +msgstr "Como podemos verificar facilmente, nosso vetor está ordenado agora::" + +#: ../../library/ctypes.rst:1084 +msgid "" +">>> for i in ia: print(i, end=\" \")\n" +"...\n" +"1 5 7 33 99\n" +">>>" msgstr "" -#: ../../library/ctypes.rst:1073 +#: ../../library/ctypes.rst:1089 msgid "" "The function factories can be used as decorator factories, so we may as well " "write::" msgstr "" +"As fábricas de funções podem ser usadas como fábricas de decoradores, então " +"também podemos escrever::" -#: ../../library/ctypes.rst:1091 +#: ../../library/ctypes.rst:1092 +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:1107 msgid "" "Make sure you keep references to :func:`CFUNCTYPE` objects as long as they " "are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be " "garbage collected, crashing your program when a callback is made." msgstr "" +"Certifique-se de manter referências aos objetos :func:`CFUNCTYPE` enquanto " +"eles forem usados a partir do código C. O :mod:`ctypes` não faz isso, e se " +"você não o fizer, eles podem ser coletados pelo coletor de lixo, travando " +"seu programa quando uma função de retorno é chamada." -#: ../../library/ctypes.rst:1095 +#: ../../library/ctypes.rst:1111 msgid "" "Also, note that if the callback function is called in a thread created " "outside of Python's control (e.g. by the foreign code that calls the " @@ -1061,36 +2223,59 @@ msgid "" "with :class:`threading.local` will *not* survive across different callbacks, " "even when those calls are made from the same C thread." msgstr "" +"Além disso, note que se a função de retorno for chamada em uma thread criada " +"fora do controle do Python (por exemplo, pelo código externo que chama a " +"função de retorno), o ctypes cria uma nova thread Python " +"\"dummy\" (fictícia) em cada invocação. Este comportamento é correto para a " +"maioria dos propósitos, mas significa que os valores armazenados com :class:" +"`threading.local` *não* sobreviverão entre diferentes funções de retorno, " +"mesmo quando essas chamadas são feitas a partir da mesma thread C." -#: ../../library/ctypes.rst:1105 +#: ../../library/ctypes.rst:1121 msgid "Accessing values exported from dlls" -msgstr "" +msgstr "Acessando valores exportados de dlls" -#: ../../library/ctypes.rst:1107 +#: ../../library/ctypes.rst:1123 msgid "" "Some shared libraries not only export functions, they also export variables. " "An example in the Python library itself is the :c:data:`Py_Version`, Python " "runtime version number encoded in a single constant integer." msgstr "" +"Algumas bibliotecas compartilhadas não exportam apenas funções, elas também " +"exportam variáveis. Um exemplo na própria biblioteca Python é a :c:data:" +"`Py_Version`, o número da versão de tempo de execução do Python codificado " +"em um único inteiro constante." -#: ../../library/ctypes.rst:1111 +#: ../../library/ctypes.rst:1127 msgid "" ":mod:`ctypes` can access values like this with the :meth:`~_CData.in_dll` " "class methods of the type. *pythonapi* is a predefined symbol giving access " "to the Python C api::" msgstr "" +":mod:`ctypes` pode acessar valores como este com os métodos de classe :meth:" +"`~_CData.in_dll` do tipo. *pythonapi* é um símbolo predefinido que dá acesso " +"à API C do Python::" -#: ../../library/ctypes.rst:1119 +#: ../../library/ctypes.rst:1131 +msgid "" +">>> version = ctypes.c_int.in_dll(ctypes.pythonapi, \"Py_Version\")\n" +">>> print(hex(version.value))\n" +"0x30c00a0" +msgstr "" + +#: ../../library/ctypes.rst:1135 msgid "" "An extended example which also demonstrates the use of pointers accesses " "the :c:data:`PyImport_FrozenModules` pointer exported by Python." msgstr "" +"Um exemplo estendido que também demonstra o uso de ponteiros acessa o " +"ponteiro :c:data:`PyImport_FrozenModules` exportado pelo Python." -#: ../../library/ctypes.rst:1122 +#: ../../library/ctypes.rst:1138 msgid "Quoting the docs for that value:" -msgstr "" +msgstr "Citando a documentação para esse valor:" -#: ../../library/ctypes.rst:1124 +#: ../../library/ctypes.rst:1140 msgid "" "This pointer is initialized to point to an array of :c:struct:`_frozen` " "records, terminated by one whose members are all ``NULL`` or zero. When a " @@ -1104,19 +2289,45 @@ msgstr "" "código de terceiros pode fazer truques com isso para fornecer uma coleção " "criada dinamicamente de módulos congelados." -#: ../../library/ctypes.rst:1129 +#: ../../library/ctypes.rst:1145 msgid "" "So manipulating this pointer could even prove useful. To restrict the " "example size, we show only how this table can be read with :mod:`ctypes`::" msgstr "" +"Então, manipular este ponteiro pode até ser útil. Para restringir o tamanho " +"do exemplo, mostramos apenas como esta tabela pode ser lida com :mod:" +"`ctypes`::" -#: ../../library/ctypes.rst:1143 +#: ../../library/ctypes.rst:1148 +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:1159 msgid "" "We have defined the :c:struct:`_frozen` data type, so we can get the pointer " "to the table::" msgstr "" +"Nós definimos tipo de dado :c:struct:`_frozen`, para que possamos obter o " +"ponteiro para a tabela::" + +#: ../../library/ctypes.rst:1162 +msgid "" +">>> FrozenTable = POINTER(struct_frozen)\n" +">>> table = FrozenTable.in_dll(pythonapi, \"_PyImport_FrozenBootstrap\")\n" +">>>" +msgstr "" -#: ../../library/ctypes.rst:1150 +#: ../../library/ctypes.rst:1166 msgid "" "Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, " "we can iterate over it, but we just have to make sure that our loop " @@ -1124,35 +2335,90 @@ msgid "" "crash with an access violation or whatever, so it's better to break out of " "the loop when we hit the ``NULL`` entry::" msgstr "" +"Como ``table`` é um ``pointer`` para o vetor de registros ``struct_frozen``, " +"nós podemos iterar sobre ele, mas só temos que nos certificar de que nosso " +"loop termine, porque ponteiros não têm tamanho. Cedo ou tarde, ele " +"provavelmente travaria com uma violação de acesso ou algo assim, então é " +"melhor sair do loop quando atingirmos a entrada ``NULL``::" -#: ../../library/ctypes.rst:1166 +#: ../../library/ctypes.rst:1172 +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:1182 msgid "" "The fact that standard Python has a frozen module and a frozen package " "(indicated by the negative ``size`` member) is not well known, it is only " "used for testing. Try it out with ``import __hello__`` for example." msgstr "" +"O fato de que o Python padrão tem um módulo congelado e um pacote congelado " +"(indicado pelo membro ``size`` negativo) não é bem conhecido, é usado apenas " +"para testes. Experimente com ``import __hello__`` por exemplo." -#: ../../library/ctypes.rst:1174 +#: ../../library/ctypes.rst:1190 msgid "Surprises" -msgstr "" +msgstr "Surpresas" -#: ../../library/ctypes.rst:1176 +#: ../../library/ctypes.rst:1192 msgid "" "There are some edges in :mod:`ctypes` where you might expect something other " "than what actually happens." msgstr "" +"Existem algumas pontos limites no :mod:`ctypes` onde você pode esperar algo " +"diferente do que realmente ocorre." -#: ../../library/ctypes.rst:1179 +#: ../../library/ctypes.rst:1195 msgid "Consider the following example::" -msgstr "" - -#: ../../library/ctypes.rst:1199 +msgstr "Considere o exemplo a seguir::" + +#: ../../library/ctypes.rst:1197 +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:1215 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 "" +"Hm. Nós com certeza esperávamos que a última instrução exibisse ``3 4 1 2``. " +"O que aconteceu? Aqui estão os passos da linha ``rc.a, rc.b = rc.b, rc.a`` " +"acima::" + +#: ../../library/ctypes.rst:1218 +msgid "" +">>> temp0, temp1 = rc.b, rc.a\n" +">>> rc.a = temp0\n" +">>> rc.b = temp1\n" +">>>" +msgstr "" -#: ../../library/ctypes.rst:1207 +#: ../../library/ctypes.rst:1223 msgid "" "Note that ``temp0`` and ``temp1`` are objects still using the internal " "buffer of the ``rc`` object above. So executing ``rc.a = temp0`` copies the " @@ -1160,27 +2426,50 @@ msgid "" "the contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't " "have the expected effect." msgstr "" +"Observe que ``temp0`` e ``temp1`` ainda são objetos que utilizam o buffer " +"interno do objeto ``rc`` acima. Portanto, executar ``rc.a = temp0`` copia o " +"conteúdo do buffer de ``temp0`` para o buffer de ``rc``. Isso, por sua vez, " +"altera o conteúdo de ``temp1``. Assim, a última atribuição ``rc.b = temp1`` " +"não produz o efeito esperado." -#: ../../library/ctypes.rst:1213 +#: ../../library/ctypes.rst:1229 msgid "" "Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays " "doesn't *copy* the sub-object, instead it retrieves a wrapper object " "accessing the root-object's underlying buffer." msgstr "" +"Tenha em mente que obter sub-objetos de estruturas, uniões e vetores não " +"copia o sub-objeto; em vez disso, recupera um objeto de encapsulamento " +"(wrapper) que acessa o buffer subjacente do objeto raiz." -#: ../../library/ctypes.rst:1217 +#: ../../library/ctypes.rst:1233 msgid "" "Another example that may behave differently from what one would expect is " "this::" msgstr "" +"Outro exemplo que pode se comportar de maneira diferente do que alguém " +"poderia esperar é o seguinte::" -#: ../../library/ctypes.rst:1229 +#: ../../library/ctypes.rst:1235 +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:1245 msgid "" "Objects instantiated from :class:`c_char_p` can only have their value set to " "bytes or integers." msgstr "" +"Objetos instanciados a partir de :class:`c_char_p` só podem ter seu valor " +"definido para bytes ou inteiros." -#: ../../library/ctypes.rst:1232 +#: ../../library/ctypes.rst:1248 msgid "" "Why is it printing ``False``? ctypes instances are objects containing a " "memory block plus some :term:`descriptor`\\s accessing the contents of the " @@ -1188,17 +2477,25 @@ msgid "" "object itself, instead the ``contents`` of the object is stored. Accessing " "the contents again constructs a new Python object each time!" msgstr "" +"Por que está imprimindo ``False``? Instâncias de ctypes são objetos que " +"contêm um bloco de memória, além de alguns :term:`descriptor`\\s que acessam " +"o conteúdo dessa memória. Armazenar um objeto Python no bloco de memória não " +"armazena o próprio objeto; em vez disso, armazena-se o seu atributo " +"``contents``. Acessar o contents novamente constrói um novo objeto Python a " +"cada vez!" -#: ../../library/ctypes.rst:1242 +#: ../../library/ctypes.rst:1258 msgid "Variable-sized data types" -msgstr "" +msgstr "Tipos de dados de tamanho variável" -#: ../../library/ctypes.rst:1244 +#: ../../library/ctypes.rst:1260 msgid "" ":mod:`ctypes` provides some support for variable-sized arrays and structures." msgstr "" +"O :mod:`ctypes` fornece algum suporte para vetores e estruturas de tamanhos " +"variável." -#: ../../library/ctypes.rst:1246 +#: ../../library/ctypes.rst:1262 msgid "" "The :func:`resize` function can be used to resize the memory buffer of an " "existing ctypes object. The function takes the object as first argument, " @@ -1206,36 +2503,79 @@ msgid "" "cannot be made smaller than the natural memory block specified by the " "objects type, a :exc:`ValueError` is raised if this is tried::" msgstr "" +"A função :func:`resize` pode ser usada para redimensionar o buffer de " +"memória de um objeto ctypes existente. A função recebe o objeto como " +"primeiro argumento, e o tamanho solicitado em bytes como o segundo " +"argumento. O bloco de memória não pode ser tornado menor do que o bloco de " +"memória natural especificado pelo tipo do objeto, um :exc:`ValueError` é " +"levantado se isso for tentado::" -#: ../../library/ctypes.rst:1266 +#: ../../library/ctypes.rst:1268 +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:1282 msgid "" "This is nice and fine, but how would one access the additional elements " "contained in this array? Since the type still only knows about 4 elements, " "we get errors accessing other elements::" msgstr "" +"Isso é bom e funcional, mas como alguém acessaria os elementos contidos " +"neste vetor? Já que o tipo ainda sabe apenas sobre 4 elementos, obtemos " +"erros ao acessar outros elementos::" -#: ../../library/ctypes.rst:1278 +#: ../../library/ctypes.rst:1286 +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:1294 msgid "" "Another way to use variable-sized data types with :mod:`ctypes` is to use " "the dynamic nature of Python, and (re-)define the data type after the " "required size is already known, on a case by case basis." msgstr "" +"Outra maneira de usar tipos de dados de tamanho variável com o :mod:`ctypes` " +"é usar a natureza dinâmica do Python, e (re)definir o tipo de dados depois " +"que o tamanho necessário já for conhecido, caso a caso." -#: ../../library/ctypes.rst:1286 +#: ../../library/ctypes.rst:1302 msgid "ctypes reference" msgstr "Referência ctypes" -#: ../../library/ctypes.rst:1292 +#: ../../library/ctypes.rst:1308 msgid "Finding shared libraries" -msgstr "" +msgstr "Encontrando bibliotecas compartilhadas" -#: ../../library/ctypes.rst:1294 +#: ../../library/ctypes.rst:1310 msgid "" "When programming in a compiled language, shared libraries are accessed when " "compiling/linking a program, and when the program is run." msgstr "" +"Ao programar em uma linguagem compilada, bibliotecas compartilhadas são " +"acessadas ao compilar/linkar (compiling/linking) um programa, e quando o " +"programa é executado." -#: ../../library/ctypes.rst:1297 +#: ../../library/ctypes.rst:1313 msgid "" "The purpose of the :func:`~ctypes.util.find_library` function is to locate a " "library in a way similar to what the compiler or runtime loader does (on " @@ -1243,14 +2583,22 @@ msgid "" "be loaded), while the ctypes library loaders act like when a program is run, " "and call the runtime loader directly." msgstr "" +"O propósito da função :func:`~ctypes.util.find_library` é localizar uma " +"biblioteca de forma semelhante ao que o compilador ou o carregador de tempo " +"de execução (runtime loader) faz (em plataformas com várias versões de uma " +"biblioteca compartilhada, a mais recente deve ser carregada), enquanto os " +"carregadores de biblioteca do ctypes agem como quando um programa é " +"executado, e chamam o carregador de tempo de execução diretamente." -#: ../../library/ctypes.rst:1303 +#: ../../library/ctypes.rst:1319 msgid "" "The :mod:`!ctypes.util` module provides a function which can help to " "determine the library to load." msgstr "" +"O módulo :mod:`!ctypes.util` fornece uma função que pode ajudar a determinar " +"a biblioteca a ser carregada." -#: ../../library/ctypes.rst:1311 +#: ../../library/ctypes.rst:1327 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 " @@ -1258,36 +2606,62 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: ../../library/ctypes.rst:1316 ../../library/ctypes.rst:1977 +#: ../../library/ctypes.rst:1332 ../../library/ctypes.rst:2038 msgid "The exact functionality is system dependent." msgstr "" -#: ../../library/ctypes.rst:1318 +#: ../../library/ctypes.rst:1334 msgid "" "On Linux, :func:`~ctypes.util.find_library` tries to run external programs " "(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library " "file. It returns the filename of the library file." msgstr "" -#: ../../library/ctypes.rst:1322 +#: ../../library/ctypes.rst:1338 msgid "" "On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used " "when searching for libraries, if a library cannot be found by any other " "means." msgstr "" -#: ../../library/ctypes.rst:1326 +#: ../../library/ctypes.rst:1342 msgid "Here are some examples::" -msgstr "Aqui estão alguns exemplos::" +msgstr "Veja alguns exemplos::" -#: ../../library/ctypes.rst:1337 +#: ../../library/ctypes.rst:1344 +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:1353 msgid "" "On macOS and Android, :func:`~ctypes.util.find_library` uses the system's " "standard naming schemes and paths to locate the library, and returns a full " "pathname if successful::" msgstr "" -#: ../../library/ctypes.rst:1352 +#: ../../library/ctypes.rst:1357 +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:1368 msgid "" "On Windows, :func:`~ctypes.util.find_library` searches along the system " "search path, and returns the full pathname, but since there is no predefined " @@ -1295,7 +2669,7 @@ msgid "" "``None``." msgstr "" -#: ../../library/ctypes.rst:1356 +#: ../../library/ctypes.rst:1372 msgid "" "If wrapping a shared library with :mod:`ctypes`, it *may* be better to " "determine the shared library name at development time, and hardcode that " @@ -1303,24 +2677,24 @@ msgid "" "to locate the library at runtime." msgstr "" -#: ../../library/ctypes.rst:1364 +#: ../../library/ctypes.rst:1380 msgid "Loading shared libraries" msgstr "" -#: ../../library/ctypes.rst:1366 +#: ../../library/ctypes.rst:1382 msgid "" "There are several ways to load shared libraries into the Python process. " "One way is to instantiate one of the following classes:" msgstr "" -#: ../../library/ctypes.rst:1372 +#: ../../library/ctypes.rst:1388 msgid "" "Instances of this class represent loaded shared libraries. Functions in " "these libraries use the standard C calling convention, and are assumed to " "return :c:expr:`int`." msgstr "" -#: ../../library/ctypes.rst:1376 +#: ../../library/ctypes.rst:1392 msgid "" "On Windows creating a :class:`CDLL` instance may fail even if the DLL name " "exists. When a dependent DLL of the loaded DLL is not found, a :exc:" @@ -1332,59 +2706,86 @@ 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:1404 ../../library/ctypes.rst:1429 +#: ../../library/ctypes.rst:1442 ../../library/ctypes.rst:1460 msgid "The *name* parameter can now be a :term:`path-like object`." msgstr "" -#: ../../library/ctypes.rst:1392 +#: ../../library/ctypes.rst:1408 msgid "" "`Microsoft DUMPBIN tool `_ -- A tool to find DLL dependents." msgstr "" -#: ../../library/ctypes.rst:1398 +#: ../../library/ctypes.rst:1414 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 "" +"Instâncias desta classe representam bibliotecas compartilhadas carregadas, " +"funções nessas bibliotecas usam a convenção de chamada ``stdcall`` e é " +"presumido que retornam o código :class:`HRESULT` específico do Windows. " +"Valores :class:`HRESULT` contêm informações especificando se a chamada da " +"função falhou ou foi bem-sucedida, juntamente com um código de erro " +"adicional. Se o valor de retorno sinalizar uma falha, um :class:`OSError` é " +"automaticamente levantado." + +#: ../../library/ctypes.rst:1421 ../../library/ctypes.rst:1438 +#: ../../library/ctypes.rst:1582 ../../library/ctypes.rst:1590 +#: ../../library/ctypes.rst:1767 ../../library/ctypes.rst:2018 +#: ../../library/ctypes.rst:2027 ../../library/ctypes.rst:2052 +#: ../../library/ctypes.rst:2061 ../../library/ctypes.rst:2070 +#: ../../library/ctypes.rst:2085 ../../library/ctypes.rst:2142 +#: ../../library/ctypes.rst:2170 ../../library/ctypes.rst:2514 +msgid "Availability" +msgstr "Disponibilidade" -#: ../../library/ctypes.rst:1405 +#: ../../library/ctypes.rst:1423 msgid "" ":exc:`WindowsError` used to be raised, which is now an alias of :exc:" "`OSError`." msgstr "" +"Costumava-se levantar :exc:`WindowsError`, que agora é um apelido de :exc:" +"`OSError`." -#: ../../library/ctypes.rst:1416 +#: ../../library/ctypes.rst:1434 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 "" +"Instâncias desta classe representam bibliotecas compartilhadas carregadas, " +"as funções nessa biblioteca usam a convenção de chamada ``stdcall`` e, por " +"padrão, é presumido que retornam :c:expr:`int`." -#: ../../library/ctypes.rst:1424 +#: ../../library/ctypes.rst:1445 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:1451 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 " "function execution the Python error flag is checked. If the error flag is " "set, a Python exception is raised." msgstr "" +"Instâncias desta classe se comportam como instâncias :class:`CDLL`, exceto " +"que o GIL do Python *não* é liberado durante a chamada da função e, após a " +"execução da função, o sinalizador de erro do Python é verificado. Se o " +"sinalizador de erro estiver definido, uma exceção Python é levantada." -#: ../../library/ctypes.rst:1435 +#: ../../library/ctypes.rst:1456 msgid "Thus, this is only useful to call Python C api functions directly." msgstr "" +"Portanto, isso só é útil para chamar funções da api C do Python diretamente." -#: ../../library/ctypes.rst:1441 +#: ../../library/ctypes.rst:1462 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 " @@ -1393,16 +2794,27 @@ msgid "" "dlopen` or :c:func:`!LoadLibrary` function is used to load the library into " "the process, and to get a handle to it." msgstr "" +"Todas essas classes podem ser instanciadas chamando-as com pelo menos um " +"argumento, o nome do caminho da biblioteca compartilhada. Se você tiver um " +"identificador existente para uma biblioteca compartilhada já carregada, ele " +"pode ser passado como o parâmetro nomeado ``handle``. Caso contrário, a " +"função :c:func:`!dlopen` ou :c:func:`!LoadLibrary` da plataforma subjacente " +"é usada para carregar a biblioteca no processo e para obter um identificador " +"para ela." -#: ../../library/ctypes.rst:1448 +#: ../../library/ctypes.rst:1469 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 " "ignored. On posix systems, RTLD_NOW is always added, and is not " "configurable." msgstr "" +"O parâmetro *mode* pode ser utilizado para especificar como a biblioteca é " +"carregada. Para detalhes, consulte a página de manual :manpage:`dlopen(3)`. " +"No Windows, *mode* é ignorado. Em sistemas posix, RTLD_NOW é sempre " +"adicionado e, não é configurável." -#: ../../library/ctypes.rst:1453 +#: ../../library/ctypes.rst:1474 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 +2824,14 @@ msgid "" "private copy, the same happens immediately after the function call." msgstr "" -#: ../../library/ctypes.rst:1460 +#: ../../library/ctypes.rst:1481 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:1485 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 +2840,7 @@ msgid "" "private copy of the windows error code." msgstr "" -#: ../../library/ctypes.rst:1470 +#: ../../library/ctypes.rst:1491 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 +2850,29 @@ msgid "" "ensure the correct library and dependencies are loaded." msgstr "" -#: ../../library/ctypes.rst:1477 +#: ../../library/ctypes.rst:1498 msgid "Added *winmode* parameter." msgstr "" -#: ../../library/ctypes.rst:1484 +#: ../../library/ctypes.rst:1505 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:1512 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:1519 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:1522 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 +2881,31 @@ msgid "" "other hand, accessing it through an index returns a new object each time::" msgstr "" -#: ../../library/ctypes.rst:1514 +#: ../../library/ctypes.rst:1528 +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:1535 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:1541 msgid "The system handle used to access the library." msgstr "" -#: ../../library/ctypes.rst:1525 +#: ../../library/ctypes.rst:1546 msgid "The name of the library passed in the constructor." msgstr "" -#: ../../library/ctypes.rst:1527 +#: ../../library/ctypes.rst:1548 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 +2913,13 @@ msgid "" "library as attribute of the loader instance." msgstr "" -#: ../../library/ctypes.rst:1535 +#: ../../library/ctypes.rst:1556 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:1559 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 +2927,39 @@ msgid "" "each time." msgstr "" -#: ../../library/ctypes.rst:1544 +#: ../../library/ctypes.rst:1565 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:1569 msgid "These prefabricated library loaders are available:" msgstr "" -#: ../../library/ctypes.rst:1553 +#: ../../library/ctypes.rst:1574 msgid "Creates :class:`CDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1559 -msgid "Windows only: Creates :class:`WinDLL` instances." +#: ../../library/ctypes.rst:1580 +msgid "Creates :class:`WinDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1565 -msgid "Windows only: Creates :class:`OleDLL` instances." +#: ../../library/ctypes.rst:1588 +msgid "Creates :class:`OleDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1571 +#: ../../library/ctypes.rst:1596 msgid "Creates :class:`PyDLL` instances." msgstr "" -#: ../../library/ctypes.rst:1574 +#: ../../library/ctypes.rst:1599 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:1605 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 +2967,7 @@ msgid "" "correct :attr:`!restype` attribute to use these functions." msgstr "" -#: ../../library/ctypes.rst:1585 ../../library/ctypes.rst:1587 +#: ../../library/ctypes.rst:1610 ../../library/ctypes.rst:1612 msgid "" "Loading a library through any of these objects raises an :ref:`auditing " "event ` ``ctypes.dlopen`` with string argument ``name``, the name " @@ -1555,56 +2977,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:1616 ../../library/ctypes.rst:1618 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:1622 ../../library/ctypes.rst:1624 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:1631 msgid "Foreign functions" msgstr "" -#: ../../library/ctypes.rst:1608 +#: ../../library/ctypes.rst:1633 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:1638 +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:1641 +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:1652 msgid "Base class for C callable foreign functions." msgstr "" -#: ../../library/ctypes.rst:1619 +#: ../../library/ctypes.rst:1654 msgid "" "Instances of foreign functions are also C compatible data types; they " "represent C function pointers." msgstr "" -#: ../../library/ctypes.rst:1622 +#: ../../library/ctypes.rst:1657 msgid "" "This behavior can be customized by assigning to special attributes of the " "foreign function object." msgstr "" -#: ../../library/ctypes.rst:1627 +#: ../../library/ctypes.rst:1662 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:1665 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 +3052,7 @@ msgid "" "callable to the :attr:`errcheck` attribute." msgstr "" -#: ../../library/ctypes.rst:1639 +#: ../../library/ctypes.rst:1674 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 +3061,7 @@ msgid "" "unspecified arguments as well." msgstr "" -#: ../../library/ctypes.rst:1645 +#: ../../library/ctypes.rst:1680 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 +3071,7 @@ msgid "" "object using ctypes conversion rules." msgstr "" -#: ../../library/ctypes.rst:1652 +#: ../../library/ctypes.rst:1687 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 +3079,44 @@ msgid "" "defining adapters that can adapt custom objects as function parameters." msgstr "" -#: ../../library/ctypes.rst:1659 +#: ../../library/ctypes.rst:1694 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:1701 msgid "" "*result* is what the foreign function returns, as specified by the :attr:`!" "restype` attribute." msgstr "" -#: ../../library/ctypes.rst:1669 +#: ../../library/ctypes.rst:1704 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:1708 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:1712 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:1719 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:1723 ../../library/ctypes.rst:1725 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 +3125,18 @@ msgid "" "hook to replace the exception with its own." msgstr "" -#: ../../library/ctypes.rst:1696 ../../library/ctypes.rst:1698 +#: ../../library/ctypes.rst:1731 ../../library/ctypes.rst:1733 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:1739 msgid "Function prototypes" msgstr "" -#: ../../library/ctypes.rst:1706 +#: ../../library/ctypes.rst:1741 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 +3147,7 @@ msgid "" "``@wrapper`` syntax. See :ref:`ctypes-callback-functions` for examples." msgstr "" -#: ../../library/ctypes.rst:1717 +#: ../../library/ctypes.rst:1752 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 +3156,37 @@ msgid "" "after the call; *use_last_error* does the same for the Windows error code." msgstr "" -#: ../../library/ctypes.rst:1727 +#: ../../library/ctypes.rst:1762 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:1772 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:1775 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:1782 msgid "" "Returns a foreign function at the specified address which must be an integer." msgstr "" -#: ../../library/ctypes.rst:1752 +#: ../../library/ctypes.rst:1789 msgid "" "Create a C callable function (a callback function) from a Python *callable*." msgstr "" -#: ../../library/ctypes.rst:1759 +#: ../../library/ctypes.rst:1796 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 +3194,7 @@ msgid "" "small integer. The second item is the shared library instance." msgstr "" -#: ../../library/ctypes.rst:1769 +#: ../../library/ctypes.rst:1806 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 +3202,114 @@ msgid "" "identifier which is used in extended error reporting." msgstr "" -#: ../../library/ctypes.rst:1774 +#: ../../library/ctypes.rst:1811 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:1815 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:1818 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:1820 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:1823 msgid "" "The first item is an integer containing a combination of direction flags for " "the parameter:" msgstr "" -#: ../../library/ctypes.rst:1789 +#: ../../library/ctypes.rst:1826 msgid "1" msgstr "1" -#: ../../library/ctypes.rst:1790 +#: ../../library/ctypes.rst:1827 msgid "Specifies an input parameter to the function." msgstr "" -#: ../../library/ctypes.rst:1792 +#: ../../library/ctypes.rst:1829 msgid "2" msgstr "2" -#: ../../library/ctypes.rst:1793 +#: ../../library/ctypes.rst:1830 msgid "Output parameter. The foreign function fills in a value." msgstr "" -#: ../../library/ctypes.rst:1795 +#: ../../library/ctypes.rst:1832 msgid "4" msgstr "4" -#: ../../library/ctypes.rst:1796 +#: ../../library/ctypes.rst:1833 msgid "Input parameter which defaults to the integer zero." msgstr "" -#: ../../library/ctypes.rst:1798 +#: ../../library/ctypes.rst:1835 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:1838 msgid "The optional third item is the default value for this parameter." msgstr "" -#: ../../library/ctypes.rst:1804 +#: ../../library/ctypes.rst:1841 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:1845 +msgid "" +"WINUSERAPI int WINAPI\n" +"MessageBoxW(\n" +" HWND hWnd,\n" +" LPCWSTR lpText,\n" +" LPCWSTR lpCaption,\n" +" UINT uType);" +msgstr "" + +#: ../../library/ctypes.rst:1852 ../../library/ctypes.rst:1875 msgid "Here is the wrapping with :mod:`ctypes`::" msgstr "" -#: ../../library/ctypes.rst:1823 +#: ../../library/ctypes.rst:1854 +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:1860 msgid "The ``MessageBox`` foreign function can now be called in these ways::" msgstr "" -#: ../../library/ctypes.rst:1829 +#: ../../library/ctypes.rst:1862 +msgid "" +">>> MessageBox()\n" +">>> MessageBox(text=\"Spam, spam, spam\")\n" +">>> MessageBox(flags=2, text=\"foo bar\")" +msgstr "" + +#: ../../library/ctypes.rst:1866 msgid "" "A second example demonstrates output parameters. The win32 " "``GetWindowRect`` function retrieves the dimensions of a specified window by " @@ -1852,7 +3317,26 @@ msgid "" "the C declaration::" msgstr "" -#: ../../library/ctypes.rst:1847 +#: ../../library/ctypes.rst:1870 +msgid "" +"WINUSERAPI BOOL WINAPI\n" +"GetWindowRect(\n" +" HWND hWnd,\n" +" LPRECT lpRect);" +msgstr "" + +#: ../../library/ctypes.rst:1877 +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:1884 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 +3344,58 @@ msgid "" "now returns a RECT instance, when called." msgstr "" -#: ../../library/ctypes.rst:1852 +#: ../../library/ctypes.rst:1889 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:1894 +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:1902 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:1908 +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:1921 msgid "Utility functions" msgstr "Funções utilitárias" -#: ../../library/ctypes.rst:1888 +#: ../../library/ctypes.rst:1925 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:1928 msgid "" "Raises an :ref:`auditing event ` ``ctypes.addressof`` with " "argument ``obj``." @@ -1896,30 +3403,34 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.addressof`` com o " "argumento ``obj``." -#: ../../library/ctypes.rst:1896 +#: ../../library/ctypes.rst:1933 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:1939 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:1943 msgid "``byref(obj, offset)`` corresponds to this C code::" msgstr "" -#: ../../library/ctypes.rst:1910 +#: ../../library/ctypes.rst:1945 +msgid "(((char *)&obj) + offset)" +msgstr "" + +#: ../../library/ctypes.rst:1947 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:1953 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,28 +3438,63 @@ msgid "" "as a pointer." msgstr "" -#: ../../library/ctypes.rst:1924 +#: ../../library/ctypes.rst:1962 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:1965 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." +"If *size* is given (and not ``None``), it must be an :class:`int`. It " +"specifies the size of the returned array." msgstr "" -#: ../../library/ctypes.rst:1930 +#: ../../library/ctypes.rst:1968 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 " -"termination character. An integer can be passed as second argument which " -"allows specifying the size of the array if the length of the bytes should " -"not be used." +"If the *init* argument is given, it must be :class:`bytes`. It is used to " +"initialize the array items. Bytes not initialized this way are set to zero " +"(NUL)." msgstr "" -#: ../../library/ctypes.rst:1935 +#: ../../library/ctypes.rst:1972 +msgid "" +"If *size* is not given (or if it is ``None``), the buffer is made one " +"element larger than *init*, effectively adding a NUL terminator." +msgstr "" + +#: ../../library/ctypes.rst:1975 +msgid "" +"If both arguments are given, *size* must not be less than ``len(init)``." +msgstr "" + +#: ../../library/ctypes.rst:1979 +msgid "" +"If *size* is equal to ``len(init)``, a NUL terminator is not added. Do not " +"treat such a buffer as a C string." +msgstr "" + +#: ../../library/ctypes.rst:1982 +msgid "For example::" +msgstr "Por exemplo::" + +#: ../../library/ctypes.rst:1984 +msgid "" +">>> bytes(create_string_buffer(2))\n" +"b'\\x00\\x00'\n" +">>> bytes(create_string_buffer(b'ab'))\n" +"b'ab\\x00'\n" +">>> bytes(create_string_buffer(b'ab', 2))\n" +"b'ab'\n" +">>> bytes(create_string_buffer(b'ab', 4))\n" +"b'ab\\x00\\x00'\n" +">>> bytes(create_string_buffer(b'abcdef', 2))\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: byte string too long" +msgstr "" + +#: ../../library/ctypes.rst:1997 msgid "" "Raises an :ref:`auditing event ` ``ctypes.create_string_buffer`` " "with arguments ``init``, ``size``." @@ -1956,28 +3502,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes." "create_string_buffer`` com os argumentos ``init``, ``size``." -#: ../../library/ctypes.rst:1940 +#: ../../library/ctypes.rst:2003 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:2006 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." +"The function takes the same arguments as :func:`~create_string_buffer` " +"except *init* must be a string and *size* counts :class:`c_wchar`." msgstr "" -#: ../../library/ctypes.rst:1946 -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 " -"is a NUL termination character. An integer can be passed as second argument " -"which allows specifying the size of the array if the length of the string " -"should not be used." -msgstr "" - -#: ../../library/ctypes.rst:1952 +#: ../../library/ctypes.rst:2009 msgid "" "Raises an :ref:`auditing event ` ``ctypes.create_unicode_buffer`` " "with arguments ``init``, ``size``." @@ -1985,21 +3522,21 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes." "create_unicode_buffer`` com os argumentos ``init``, ``size``." -#: ../../library/ctypes.rst:1957 +#: ../../library/ctypes.rst:2014 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:2023 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:2033 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 +3544,41 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: ../../library/ctypes.rst:1983 +#: ../../library/ctypes.rst:2044 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:2048 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:2057 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:2066 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:2075 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:2078 msgid "" "Raises an :ref:`auditing event ` ``ctypes.get_errno`` with no " "arguments." @@ -2049,13 +3586,13 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.get_errno`` sem " "argumentos." -#: ../../library/ctypes.rst:2014 +#: ../../library/ctypes.rst:2082 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:2087 msgid "" "Raises an :ref:`auditing event ` ``ctypes.get_last_error`` with no " "arguments." @@ -2063,40 +3600,40 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.get_last_error`` " "sem argumentos." -#: ../../library/ctypes.rst:2021 +#: ../../library/ctypes.rst:2092 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:2099 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:2106 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:2113 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:2116 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:2122 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 +3641,13 @@ msgid "" "but it is possible to enlarge the buffer." msgstr "" -#: ../../library/ctypes.rst:2059 +#: ../../library/ctypes.rst:2130 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:2133 msgid "" "Raises an :ref:`auditing event ` ``ctypes.set_errno`` with " "argument ``errno``." @@ -2118,14 +3655,14 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.set_errno`` com o " "argumento ``errno``." -#: ../../library/ctypes.rst:2067 +#: ../../library/ctypes.rst:2138 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:2144 msgid "" "Raises an :ref:`auditing event ` ``ctypes.set_last_error`` with " "argument ``error``." @@ -2133,19 +3670,19 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.set_last_error`` " "com o argumento ``error``." -#: ../../library/ctypes.rst:2076 +#: ../../library/ctypes.rst:2149 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:2155 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:2159 msgid "" "Raises an :ref:`auditing event ` ``ctypes.string_at`` with " "arguments ``ptr``, ``size``." @@ -2153,29 +3690,28 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.string_at`` com os " "argumentos ``ptr``, ``size``." -#: ../../library/ctypes.rst:2091 +#: ../../library/ctypes.rst:2164 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:2172 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:2179 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:2184 msgid "" "Raises an :ref:`auditing event ` ``ctypes.wstring_at`` with " "arguments ``ptr``, ``size``." @@ -2183,11 +3719,11 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.wstring_at`` com " "os argumentos ``ptr``, ``size``." -#: ../../library/ctypes.rst:2115 +#: ../../library/ctypes.rst:2190 msgid "Data types" msgstr "" -#: ../../library/ctypes.rst:2120 +#: ../../library/ctypes.rst:2195 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 +3733,13 @@ msgid "" "alive in case the memory block contains pointers." msgstr "" -#: ../../library/ctypes.rst:2127 +#: ../../library/ctypes.rst:2202 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:2207 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 +3748,7 @@ msgid "" "exc:`ValueError` is raised." msgstr "" -#: ../../library/ctypes.rst:2138 ../../library/ctypes.rst:2148 +#: ../../library/ctypes.rst:2213 ../../library/ctypes.rst:2223 msgid "" "Raises an :ref:`auditing event ` ``ctypes.cdata/buffer`` with " "arguments ``pointer``, ``size``, ``offset``." @@ -2220,7 +3756,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``ctypes.cdata/buffer`` com " "os argumentos ``pointer``, ``size``, ``offset``." -#: ../../library/ctypes.rst:2142 +#: ../../library/ctypes.rst:2217 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 +3764,13 @@ msgid "" "If the source buffer is not large enough a :exc:`ValueError` is raised." msgstr "" -#: ../../library/ctypes.rst:2152 +#: ../../library/ctypes.rst:2227 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:2230 ../../library/ctypes.rst:2232 msgid "" "This method, and others that indirectly call this method, raises an :ref:" "`auditing event ` ``ctypes.cdata`` with argument ``address``." @@ -2243,33 +3779,33 @@ msgstr "" "`evento de auditoria ` ``ctypes.cdata`` com o argumento " "``address``." -#: ../../library/ctypes.rst:2163 +#: ../../library/ctypes.rst:2238 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:2243 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:2249 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:2253 msgid "Common instance variables of ctypes data types:" msgstr "" -#: ../../library/ctypes.rst:2182 +#: ../../library/ctypes.rst:2257 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 +3813,13 @@ msgid "" "block." msgstr "" -#: ../../library/ctypes.rst:2189 +#: ../../library/ctypes.rst:2264 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:2269 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 +3827,7 @@ msgid "" "dictionary." msgstr "" -#: ../../library/ctypes.rst:2207 +#: ../../library/ctypes.rst:2282 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 +3836,11 @@ msgid "" "types that are not and do not contain pointers can now be pickled." msgstr "" -#: ../../library/ctypes.rst:2213 +#: ../../library/ctypes.rst:2288 msgid "Instances have a single attribute:" msgstr "" -#: ../../library/ctypes.rst:2217 +#: ../../library/ctypes.rst:2292 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 +3848,7 @@ msgid "" "bytes object or string." msgstr "" -#: ../../library/ctypes.rst:2222 +#: ../../library/ctypes.rst:2297 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 +3856,17 @@ msgid "" "true for all other ctypes object instances." msgstr "" -#: ../../library/ctypes.rst:2228 +#: ../../library/ctypes.rst:2303 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:2311 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 +3874,25 @@ msgid "" "you can get the value of the pointer by accessing the ``value`` attribute." msgstr "" -#: ../../library/ctypes.rst:2241 +#: ../../library/ctypes.rst:2316 msgid "These are the fundamental ctypes data types:" msgstr "" -#: ../../library/ctypes.rst:2245 +#: ../../library/ctypes.rst:2320 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:2327 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:2334 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 +3900,182 @@ msgid "" "integer address, or a bytes object." msgstr "" -#: ../../library/ctypes.rst:2267 +#: ../../library/ctypes.rst:2342 msgid "" "Represents the C :c:expr:`double` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: ../../library/ctypes.rst:2273 +#: ../../library/ctypes.rst:2348 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:2354 msgid "" "Represents the C :c:expr:`float` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: ../../library/ctypes.rst:2285 +#: ../../library/ctypes.rst:2360 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:2367 msgid "" -"Represents the C 8-bit :c:expr:`signed int` datatype. Usually an alias for :" +"Represents the C 8-bit :c:expr:`signed int` datatype. It is an alias for :" "class:`c_byte`." msgstr "" -#: ../../library/ctypes.rst:2298 +#: ../../library/ctypes.rst:2373 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:2379 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:2385 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:2391 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:2397 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:2403 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:2409 msgid "Represents the C :c:type:`size_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2339 +#: ../../library/ctypes.rst:2414 msgid "Represents the C :c:type:`ssize_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2346 +#: ../../library/ctypes.rst:2421 msgid "Represents the C :c:type:`time_t` datatype." msgstr "" -#: ../../library/ctypes.rst:2353 +#: ../../library/ctypes.rst:2428 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:2435 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:2442 msgid "" -"Represents the C 8-bit :c:expr:`unsigned int` datatype. Usually an alias " -"for :class:`c_ubyte`." +"Represents the C 8-bit :c:expr:`unsigned int` datatype. It is an alias for :" +"class:`c_ubyte`." msgstr "" -#: ../../library/ctypes.rst:2373 +#: ../../library/ctypes.rst:2448 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:2454 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:2460 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:2466 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:2472 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:2478 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:2484 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:2490 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:2497 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:2504 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:2511 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:2519 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:2522 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 +4083,41 @@ msgid "" "are also defined." msgstr "" -#: ../../library/ctypes.rst:2453 +#: ../../library/ctypes.rst:2530 msgid "Structured data types" msgstr "" -#: ../../library/ctypes.rst:2458 +#: ../../library/ctypes.rst:2535 msgid "Abstract base class for unions in native byte order." msgstr "" -#: ../../library/ctypes.rst:2463 +#: ../../library/ctypes.rst:2540 msgid "Abstract base class for unions in *big endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2469 +#: ../../library/ctypes.rst:2546 msgid "Abstract base class for unions in *little endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2475 +#: ../../library/ctypes.rst:2552 msgid "Abstract base class for structures in *big endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2480 +#: ../../library/ctypes.rst:2557 msgid "Abstract base class for structures in *little endian* byte order." msgstr "" -#: ../../library/ctypes.rst:2482 +#: ../../library/ctypes.rst:2559 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:2565 msgid "Abstract base class for structures in *native* byte order." msgstr "" -#: ../../library/ctypes.rst:2490 +#: ../../library/ctypes.rst:2567 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 +4125,43 @@ msgid "" "the fields by direct attribute accesses. These are the" msgstr "" -#: ../../library/ctypes.rst:2498 +#: ../../library/ctypes.rst:2575 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:2579 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:2583 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:2586 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:2590 +msgid "" +"class List(Structure):\n" +" pass\n" +"List._fields_ = [(\"pnext\", POINTER(List)),\n" +" ...\n" +" ]" +msgstr "" + +#: ../../library/ctypes.rst:2596 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 +4169,14 @@ msgid "" "raise an AttributeError." msgstr "" -#: ../../library/ctypes.rst:2524 +#: ../../library/ctypes.rst:2601 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:2608 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 +4184,21 @@ msgid "" "attribute to 0 is the same as not setting it at all." msgstr "" -#: ../../library/ctypes.rst:2539 +#: ../../library/ctypes.rst:2616 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:2624 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:2628 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 +4206,24 @@ msgid "" "structure or union field." msgstr "" -#: ../../library/ctypes.rst:2554 +#: ../../library/ctypes.rst:2633 msgid "Here is an example type (Windows)::" msgstr "" -#: ../../library/ctypes.rst:2567 +#: ../../library/ctypes.rst:2635 +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:2646 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 +4233,15 @@ msgid "" "temporary union instance::" msgstr "" -#: ../../library/ctypes.rst:2579 +#: ../../library/ctypes.rst:2653 +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:2658 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 +4249,7 @@ msgid "" "of the base class." msgstr "" -#: ../../library/ctypes.rst:2584 +#: ../../library/ctypes.rst:2663 msgid "" "Structure and union constructors accept both positional and keyword " "arguments. Positional arguments are used to initialize member fields in the " @@ -2693,15 +4259,15 @@ msgid "" "names not present in :attr:`_fields_`." msgstr "" -#: ../../library/ctypes.rst:2595 +#: ../../library/ctypes.rst:2674 msgid "Arrays and pointers" msgstr "" -#: ../../library/ctypes.rst:2599 +#: ../../library/ctypes.rst:2678 msgid "Abstract base class for arrays." msgstr "" -#: ../../library/ctypes.rst:2601 +#: ../../library/ctypes.rst:2680 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 +4277,46 @@ msgid "" "an :class:`Array`." msgstr "" -#: ../../library/ctypes.rst:2611 +#: ../../library/ctypes.rst:2690 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:2697 msgid "Specifies the type of each element in the array." msgstr "" -#: ../../library/ctypes.rst:2621 +#: ../../library/ctypes.rst:2700 msgid "" "Array subclass constructors accept positional arguments, used to initialize " "the elements in order." msgstr "" -#: ../../library/ctypes.rst:2626 +#: ../../library/ctypes.rst:2705 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:2709 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:2715 msgid "Private, abstract base class for pointers." msgstr "" -#: ../../library/ctypes.rst:2638 +#: ../../library/ctypes.rst:2717 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:2721 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 +4325,11 @@ msgid "" "probably crash with an access violation (if you're lucky)." msgstr "" -#: ../../library/ctypes.rst:2652 +#: ../../library/ctypes.rst:2731 msgid "Specifies the type pointed to." msgstr "" -#: ../../library/ctypes.rst:2656 +#: ../../library/ctypes.rst:2735 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..070106e8d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..812868e77 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..2c5b4874d 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 +# python-doc bot, 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -307,7 +294,7 @@ msgid "" "const:`BUTTON_ALT`." msgstr "" -#: ../../library/curses.rst:215 ../../library/curses.rst:1776 +#: ../../library/curses.rst:215 ../../library/curses.rst:1777 msgid "" "The ``BUTTON5_*`` constants are now exposed if they are provided by the " "underlying curses library." @@ -810,46 +797,46 @@ msgstr "" msgid "Window Objects" msgstr "" -#: ../../library/curses.rst:706 +#: ../../library/curses.rst:708 msgid "" "Window objects, as returned by :func:`initscr` and :func:`newwin` above, " "have the following methods and attributes:" msgstr "" -#: ../../library/curses.rst:713 +#: ../../library/curses.rst:715 msgid "" "Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any " "character previously painted at that location. By default, the character " "position and attributes are the current settings for the window object." msgstr "" -#: ../../library/curses.rst:719 +#: ../../library/curses.rst:721 msgid "" "Writing outside the window, subwindow, or pad raises a :exc:`curses.error`. " "Attempting to write to the lower right corner of a window, subwindow, or pad " "will cause an exception to be raised after the character is printed." msgstr "" -#: ../../library/curses.rst:727 +#: ../../library/curses.rst:729 msgid "" "Paint at most *n* characters of the character string *str* at ``(y, x)`` " "with attributes *attr*, overwriting anything previously on the display." msgstr "" -#: ../../library/curses.rst:735 +#: ../../library/curses.rst:737 msgid "" "Paint the character string *str* at ``(y, x)`` with attributes *attr*, " "overwriting anything previously on the display." msgstr "" -#: ../../library/curses.rst:740 +#: ../../library/curses.rst:742 msgid "" "Writing outside the window, subwindow, or pad raises :exc:`curses.error`. " "Attempting to write to the lower right corner of a window, subwindow, or pad " "will cause an exception to be raised after the string is printed." msgstr "" -#: ../../library/curses.rst:744 +#: ../../library/curses.rst:746 msgid "" "A `bug in ncurses `_, the backend for " "this Python module, can cause SegFaults when resizing windows. This is fixed " @@ -859,44 +846,44 @@ msgid "" "line." msgstr "" -#: ../../library/curses.rst:754 +#: ../../library/curses.rst:756 msgid "" "Remove attribute *attr* from the \"background\" set applied to all writes to " "the current window." msgstr "" -#: ../../library/curses.rst:760 +#: ../../library/curses.rst:762 msgid "" -"Add attribute *attr* from the \"background\" set applied to all writes to " -"the current window." +"Add attribute *attr* to the \"background\" set applied to all writes to the " +"current window." msgstr "" -#: ../../library/curses.rst:766 +#: ../../library/curses.rst:768 msgid "" "Set the \"background\" set of attributes to *attr*. This set is initially " "``0`` (no attributes)." msgstr "" -#: ../../library/curses.rst:772 +#: ../../library/curses.rst:774 msgid "" "Set the background property of the window to the character *ch*, with " "attributes *attr*. The change is then applied to every character position " "in that window:" msgstr "" -#: ../../library/curses.rst:776 +#: ../../library/curses.rst:778 msgid "" "The attribute of every character in the window is changed to the new " "background attribute." msgstr "" -#: ../../library/curses.rst:779 +#: ../../library/curses.rst:781 msgid "" "Wherever the former background character appears, it is changed to the new " "background character." msgstr "" -#: ../../library/curses.rst:785 +#: ../../library/curses.rst:787 msgid "" "Set the window's background. A window's background consists of a character " "and any combination of attributes. The attribute part of the background is " @@ -907,128 +894,128 @@ msgid "" "delete line/character operations." msgstr "" -#: ../../library/curses.rst:795 +#: ../../library/curses.rst:797 msgid "" "Draw a border around the edges of the window. Each parameter specifies the " "character to use for a specific part of the border; see the table below for " "more details." msgstr "" -#: ../../library/curses.rst:801 +#: ../../library/curses.rst:803 msgid "" "A ``0`` value for any parameter will cause the default character to be used " "for that parameter. Keyword parameters can *not* be used. The defaults are " "listed in this table:" msgstr "" -#: ../../library/curses.rst:806 +#: ../../library/curses.rst:808 msgid "Parameter" msgstr "" -#: ../../library/curses.rst:806 +#: ../../library/curses.rst:808 msgid "Description" msgstr "Descrição" -#: ../../library/curses.rst:806 +#: ../../library/curses.rst:808 msgid "Default value" msgstr "Valor padrão" -#: ../../library/curses.rst:808 +#: ../../library/curses.rst:810 msgid "*ls*" msgstr "" -#: ../../library/curses.rst:808 +#: ../../library/curses.rst:810 msgid "Left side" msgstr "" -#: ../../library/curses.rst:808 ../../library/curses.rst:810 +#: ../../library/curses.rst:810 ../../library/curses.rst:812 msgid ":const:`ACS_VLINE`" msgstr ":const:`ACS_VLINE`" -#: ../../library/curses.rst:810 +#: ../../library/curses.rst:812 msgid "*rs*" msgstr "" -#: ../../library/curses.rst:810 +#: ../../library/curses.rst:812 msgid "Right side" msgstr "" -#: ../../library/curses.rst:812 +#: ../../library/curses.rst:814 msgid "*ts*" msgstr "" -#: ../../library/curses.rst:812 +#: ../../library/curses.rst:814 msgid "Top" msgstr "" -#: ../../library/curses.rst:812 ../../library/curses.rst:814 +#: ../../library/curses.rst:814 ../../library/curses.rst:816 msgid ":const:`ACS_HLINE`" msgstr ":const:`ACS_HLINE`" -#: ../../library/curses.rst:814 +#: ../../library/curses.rst:816 msgid "*bs*" msgstr "" -#: ../../library/curses.rst:814 +#: ../../library/curses.rst:816 msgid "Bottom" msgstr "" -#: ../../library/curses.rst:816 +#: ../../library/curses.rst:818 msgid "*tl*" msgstr "" -#: ../../library/curses.rst:816 +#: ../../library/curses.rst:818 msgid "Upper-left corner" msgstr "" -#: ../../library/curses.rst:816 +#: ../../library/curses.rst:818 msgid ":const:`ACS_ULCORNER`" msgstr ":const:`ACS_ULCORNER`" -#: ../../library/curses.rst:818 +#: ../../library/curses.rst:820 msgid "*tr*" msgstr "*tr*" -#: ../../library/curses.rst:818 +#: ../../library/curses.rst:820 msgid "Upper-right corner" msgstr "" -#: ../../library/curses.rst:818 +#: ../../library/curses.rst:820 msgid ":const:`ACS_URCORNER`" msgstr ":const:`ACS_URCORNER`" -#: ../../library/curses.rst:820 +#: ../../library/curses.rst:822 msgid "*bl*" msgstr "" -#: ../../library/curses.rst:820 +#: ../../library/curses.rst:822 msgid "Bottom-left corner" msgstr "" -#: ../../library/curses.rst:820 +#: ../../library/curses.rst:822 msgid ":const:`ACS_LLCORNER`" msgstr ":const:`ACS_LLCORNER`" -#: ../../library/curses.rst:822 +#: ../../library/curses.rst:824 msgid "*br*" msgstr "" -#: ../../library/curses.rst:822 +#: ../../library/curses.rst:824 msgid "Bottom-right corner" msgstr "" -#: ../../library/curses.rst:822 +#: ../../library/curses.rst:824 msgid ":const:`ACS_LRCORNER`" msgstr ":const:`ACS_LRCORNER`" -#: ../../library/curses.rst:828 +#: ../../library/curses.rst:830 msgid "" "Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* " "and *bs* are *horch*. The default corner characters are always used by this " "function." msgstr "" -#: ../../library/curses.rst:837 +#: ../../library/curses.rst:839 msgid "" "Set the attributes of *num* characters at the current cursor position, or at " "position ``(y, x)`` if supplied. If *num* is not given or is ``-1``, the " @@ -1038,45 +1025,45 @@ msgid "" "be redisplayed by the next window refresh." msgstr "" -#: ../../library/curses.rst:847 +#: ../../library/curses.rst:849 msgid "" "Like :meth:`erase`, but also cause the whole window to be repainted upon " "next call to :meth:`refresh`." msgstr "" -#: ../../library/curses.rst:853 +#: ../../library/curses.rst:855 msgid "" "If *flag* is ``True``, the next call to :meth:`refresh` will clear the " "window completely." msgstr "" -#: ../../library/curses.rst:859 +#: ../../library/curses.rst:861 msgid "" "Erase from cursor to the end of the window: all lines below the cursor are " "deleted, and then the equivalent of :meth:`clrtoeol` is performed." msgstr "" -#: ../../library/curses.rst:865 +#: ../../library/curses.rst:867 msgid "Erase from cursor to the end of the line." msgstr "" -#: ../../library/curses.rst:870 +#: ../../library/curses.rst:872 msgid "" "Update the current cursor position of all the ancestors of the window to " "reflect the current cursor position of the window." msgstr "" -#: ../../library/curses.rst:876 +#: ../../library/curses.rst:878 msgid "Delete any character at ``(y, x)``." msgstr "" -#: ../../library/curses.rst:881 +#: ../../library/curses.rst:883 msgid "" "Delete the line under the cursor. All following lines are moved up by one " "line." msgstr "" -#: ../../library/curses.rst:887 +#: ../../library/curses.rst:889 msgid "" "An abbreviation for \"derive window\", :meth:`derwin` is the same as " "calling :meth:`subwin`, except that *begin_y* and *begin_x* are relative to " @@ -1084,13 +1071,13 @@ msgid "" "a window object for the derived window." msgstr "" -#: ../../library/curses.rst:895 +#: ../../library/curses.rst:897 msgid "" "Add character *ch* with attribute *attr*, and immediately call :meth:" "`refresh` on the window." msgstr "" -#: ../../library/curses.rst:901 +#: ../../library/curses.rst:903 msgid "" "Test whether the given pair of screen-relative character-cell coordinates " "are enclosed by the given window, returning ``True`` or ``False``. It is " @@ -1098,11 +1085,11 @@ msgid "" "location of a mouse event." msgstr "" -#: ../../library/curses.rst:906 +#: ../../library/curses.rst:908 msgid "Previously it returned ``1`` or ``0`` instead of ``True`` or ``False``." msgstr "" -#: ../../library/curses.rst:912 +#: ../../library/curses.rst:914 msgid "" "Encoding used to encode method arguments (Unicode strings and characters). " "The encoding attribute is inherited from the parent window when a subwindow " @@ -1110,19 +1097,19 @@ msgid "" "locale encoding is used (see :func:`locale.getencoding`)." msgstr "" -#: ../../library/curses.rst:922 +#: ../../library/curses.rst:924 msgid "Clear the window." msgstr "" -#: ../../library/curses.rst:927 +#: ../../library/curses.rst:929 msgid "Return a tuple ``(y, x)`` of coordinates of upper-left corner." msgstr "" -#: ../../library/curses.rst:932 +#: ../../library/curses.rst:934 msgid "Return the given window's current background character/attribute pair." msgstr "" -#: ../../library/curses.rst:937 +#: ../../library/curses.rst:939 msgid "" "Get a character. Note that the integer returned does *not* have to be in " "ASCII range: function keys, keypad keys and so on are represented by numbers " @@ -1130,14 +1117,14 @@ msgid "" "otherwise wait until a key is pressed." msgstr "" -#: ../../library/curses.rst:945 +#: ../../library/curses.rst:947 msgid "" "Get a wide character. Return a character for most keys, or an integer for " "function keys, keypad keys, and other special keys. In no-delay mode, raise " "an exception if there is no input." msgstr "" -#: ../../library/curses.rst:954 +#: ../../library/curses.rst:956 msgid "" "Get a character, returning a string instead of an integer, as :meth:`getch` " "does. Function keys, keypad keys and other special keys return a multibyte " @@ -1145,35 +1132,35 @@ msgid "" "there is no input." msgstr "" -#: ../../library/curses.rst:962 +#: ../../library/curses.rst:964 msgid "Return a tuple ``(y, x)`` of the height and width of the window." msgstr "" -#: ../../library/curses.rst:967 +#: ../../library/curses.rst:969 msgid "" "Return the beginning coordinates of this window relative to its parent " "window as a tuple ``(y, x)``. Return ``(-1, -1)`` if this window has no " "parent." msgstr "" -#: ../../library/curses.rst:977 +#: ../../library/curses.rst:979 msgid "" "Read a bytes object from the user, with primitive line editing capacity." msgstr "" -#: ../../library/curses.rst:982 +#: ../../library/curses.rst:984 msgid "" "Return a tuple ``(y, x)`` of current cursor position relative to the " "window's upper-left corner." msgstr "" -#: ../../library/curses.rst:989 +#: ../../library/curses.rst:991 msgid "" "Display a horizontal line starting at ``(y, x)`` with length *n* consisting " "of the character *ch*." msgstr "" -#: ../../library/curses.rst:995 +#: ../../library/curses.rst:997 msgid "" "If *flag* is ``False``, curses no longer considers using the hardware insert/" "delete character feature of the terminal; if *flag* is ``True``, use of " @@ -1181,13 +1168,13 @@ msgid "" "initialized, use of character insert/delete is enabled by default." msgstr "" -#: ../../library/curses.rst:1003 +#: ../../library/curses.rst:1005 msgid "" "If *flag* is ``True``, :mod:`curses` will try and use hardware line editing " "facilities. Otherwise, line insertion/deletion are disabled." msgstr "" -#: ../../library/curses.rst:1009 +#: ../../library/curses.rst:1011 msgid "" "If *flag* is ``True``, any change in the window image automatically causes " "the window to be refreshed; you no longer have to call :meth:`refresh` " @@ -1195,19 +1182,19 @@ msgid "" "calls to wrefresh. This option is disabled by default." msgstr "" -#: ../../library/curses.rst:1017 +#: ../../library/curses.rst:1019 msgid "" "Return the character at the given position in the window. The bottom 8 bits " "are the character proper, and upper bits are the attributes." msgstr "" -#: ../../library/curses.rst:1024 +#: ../../library/curses.rst:1026 msgid "" "Paint character *ch* at ``(y, x)`` with attributes *attr*, moving the line " "from position *x* right by one character." msgstr "" -#: ../../library/curses.rst:1030 +#: ../../library/curses.rst:1032 msgid "" "Insert *nlines* lines into the specified window above the current line. The " "*nlines* bottom lines are lost. For negative *nlines*, delete *nlines* " @@ -1216,13 +1203,13 @@ msgid "" "remains the same." msgstr "" -#: ../../library/curses.rst:1039 +#: ../../library/curses.rst:1041 msgid "" "Insert a blank line under the cursor. All following lines are moved down by " "one line." msgstr "" -#: ../../library/curses.rst:1046 +#: ../../library/curses.rst:1048 msgid "" "Insert a character string (as many characters as will fit on the line) " "before the character under the cursor, up to *n* characters. If *n* is " @@ -1232,7 +1219,7 @@ msgid "" "if specified)." msgstr "" -#: ../../library/curses.rst:1056 +#: ../../library/curses.rst:1058 msgid "" "Insert a character string (as many characters as will fit on the line) " "before the character under the cursor. All characters to the right of the " @@ -1241,7 +1228,7 @@ msgid "" "specified)." msgstr "" -#: ../../library/curses.rst:1065 +#: ../../library/curses.rst:1067 msgid "" "Return a bytes object of characters, extracted from the window starting at " "the current cursor position, or at *y*, *x* if specified. Attributes are " @@ -1249,76 +1236,76 @@ msgid "" "string at most *n* characters long (exclusive of the trailing NUL)." msgstr "" -#: ../../library/curses.rst:1073 +#: ../../library/curses.rst:1075 msgid "" "Return ``True`` if the specified line was modified since the last call to :" "meth:`refresh`; otherwise return ``False``. Raise a :exc:`curses.error` " "exception if *line* is not valid for the given window." msgstr "" -#: ../../library/curses.rst:1080 +#: ../../library/curses.rst:1082 msgid "" "Return ``True`` if the specified window was modified since the last call to :" "meth:`refresh`; otherwise return ``False``." msgstr "" -#: ../../library/curses.rst:1086 +#: ../../library/curses.rst:1088 msgid "" "If *flag* is ``True``, escape sequences generated by some keys (keypad, " "function keys) will be interpreted by :mod:`curses`. If *flag* is ``False``, " "escape sequences will be left as is in the input stream." msgstr "" -#: ../../library/curses.rst:1093 +#: ../../library/curses.rst:1095 msgid "" "If *flag* is ``True``, cursor is left where it is on update, instead of " "being at \"cursor position.\" This reduces cursor movement where possible. " "If possible the cursor will be made invisible." msgstr "" -#: ../../library/curses.rst:1097 +#: ../../library/curses.rst:1099 msgid "" "If *flag* is ``False``, cursor will always be at \"cursor position\" after " "an update." msgstr "" -#: ../../library/curses.rst:1102 +#: ../../library/curses.rst:1104 msgid "Move cursor to ``(new_y, new_x)``." msgstr "" -#: ../../library/curses.rst:1107 +#: ../../library/curses.rst:1109 msgid "" "Move the window inside its parent window. The screen-relative parameters of " "the window are not changed. This routine is used to display different parts " "of the parent window at the same physical position on the screen." msgstr "" -#: ../../library/curses.rst:1114 +#: ../../library/curses.rst:1116 msgid "Move the window so its upper-left corner is at ``(new_y, new_x)``." msgstr "" -#: ../../library/curses.rst:1119 +#: ../../library/curses.rst:1121 msgid "If *flag* is ``True``, :meth:`getch` will be non-blocking." msgstr "" -#: ../../library/curses.rst:1124 +#: ../../library/curses.rst:1126 msgid "If *flag* is ``True``, escape sequences will not be timed out." msgstr "" -#: ../../library/curses.rst:1126 +#: ../../library/curses.rst:1128 msgid "" "If *flag* is ``False``, after a few milliseconds, an escape sequence will " "not be interpreted, and will be left in the input stream as is." msgstr "" -#: ../../library/curses.rst:1132 +#: ../../library/curses.rst:1134 msgid "" "Mark for refresh but wait. This function updates the data structure " "representing the desired state of the window, but does not force an update " "of the physical screen. To accomplish that, call :func:`doupdate`." msgstr "" -#: ../../library/curses.rst:1139 +#: ../../library/curses.rst:1141 msgid "" "Overlay the window on top of *destwin*. The windows need not be the same " "size, only the overlapping region is copied. This copy is non-destructive, " @@ -1326,7 +1313,7 @@ msgid "" "contents of *destwin*." msgstr "" -#: ../../library/curses.rst:1144 +#: ../../library/curses.rst:1146 msgid "" "To get fine-grained control over the copied region, the second form of :meth:" "`overlay` can be used. *sminrow* and *smincol* are the upper-left " @@ -1334,7 +1321,7 @@ msgid "" "in the destination window." msgstr "" -#: ../../library/curses.rst:1152 +#: ../../library/curses.rst:1154 msgid "" "Overwrite the window on top of *destwin*. The windows need not be the same " "size, in which case only the overlapping region is copied. This copy is " @@ -1342,7 +1329,7 @@ msgid "" "the old contents of *destwin*." msgstr "" -#: ../../library/curses.rst:1157 +#: ../../library/curses.rst:1159 msgid "" "To get fine-grained control over the copied region, the second form of :meth:" "`overwrite` can be used. *sminrow* and *smincol* are the upper-left " @@ -1350,31 +1337,31 @@ msgid "" "the destination window." msgstr "" -#: ../../library/curses.rst:1165 +#: ../../library/curses.rst:1167 msgid "" "Write all data associated with the window into the provided file object. " "This information can be later retrieved using the :func:`getwin` function." msgstr "" -#: ../../library/curses.rst:1171 +#: ../../library/curses.rst:1173 msgid "" "Indicate that the *num* screen lines, starting at line *beg*, are corrupted " "and should be completely redrawn on the next :meth:`refresh` call." msgstr "" -#: ../../library/curses.rst:1177 +#: ../../library/curses.rst:1179 msgid "" "Touch the entire window, causing it to be completely redrawn on the next :" "meth:`refresh` call." msgstr "" -#: ../../library/curses.rst:1183 +#: ../../library/curses.rst:1185 msgid "" "Update the display immediately (sync actual screen with previous drawing/" "deleting methods)." msgstr "" -#: ../../library/curses.rst:1186 +#: ../../library/curses.rst:1188 msgid "" "The 6 optional arguments can only be specified when the window is a pad " "created with :func:`newpad`. The additional parameters are needed to " @@ -1389,7 +1376,7 @@ msgid "" "*smincol* are treated as if they were zero." msgstr "" -#: ../../library/curses.rst:1200 +#: ../../library/curses.rst:1202 msgid "" "Reallocate storage for a curses window to adjust its dimensions to the " "specified values. If either dimension is larger than the current values, " @@ -1397,11 +1384,11 @@ msgid "" "rendition (as set by :meth:`bkgdset`) merged into them." msgstr "" -#: ../../library/curses.rst:1208 +#: ../../library/curses.rst:1210 msgid "Scroll the screen or scrolling region upward by *lines* lines." msgstr "" -#: ../../library/curses.rst:1213 +#: ../../library/curses.rst:1215 msgid "" "Control what happens when the cursor of a window is moved off the edge of " "the window or scrolling region, either as a result of a newline action on " @@ -1411,54 +1398,54 @@ msgid "" "scrolling effect on the terminal, it is also necessary to call :meth:`idlok`." msgstr "" -#: ../../library/curses.rst:1223 +#: ../../library/curses.rst:1225 msgid "" "Set the scrolling region from line *top* to line *bottom*. All scrolling " "actions will take place in this region." msgstr "" -#: ../../library/curses.rst:1229 +#: ../../library/curses.rst:1231 msgid "" "Turn off the standout attribute. On some terminals this has the side effect " "of turning off all attributes." msgstr "" -#: ../../library/curses.rst:1235 +#: ../../library/curses.rst:1237 msgid "Turn on attribute *A_STANDOUT*." msgstr "" -#: ../../library/curses.rst:1241 ../../library/curses.rst:1248 +#: ../../library/curses.rst:1243 ../../library/curses.rst:1250 msgid "" "Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, " "and whose width/height is *ncols*/*nlines*." msgstr "" -#: ../../library/curses.rst:1251 +#: ../../library/curses.rst:1253 msgid "" "By default, the sub-window will extend from the specified position to the " "lower right corner of the window." msgstr "" -#: ../../library/curses.rst:1257 +#: ../../library/curses.rst:1259 msgid "" "Touch each location in the window that has been touched in any of its " "ancestor windows. This routine is called by :meth:`refresh`, so it should " "almost never be necessary to call it manually." msgstr "" -#: ../../library/curses.rst:1264 +#: ../../library/curses.rst:1266 msgid "" "If *flag* is ``True``, then :meth:`syncup` is called automatically whenever " "there is a change in the window." msgstr "" -#: ../../library/curses.rst:1270 +#: ../../library/curses.rst:1272 msgid "" "Touch all locations in ancestors of the window that have been changed in " "the window." msgstr "" -#: ../../library/curses.rst:1276 +#: ../../library/curses.rst:1278 msgid "" "Set blocking or non-blocking read behavior for the window. If *delay* is " "negative, blocking read is used (which will wait indefinitely for input). " @@ -1468,7 +1455,7 @@ msgid "" "still no input at the end of that time." msgstr "" -#: ../../library/curses.rst:1286 +#: ../../library/curses.rst:1288 msgid "" "Pretend *count* lines have been changed, starting with line *start*. If " "*changed* is supplied, it specifies whether the affected lines are marked as " @@ -1476,49 +1463,49 @@ msgid "" "``=False``)." msgstr "" -#: ../../library/curses.rst:1293 +#: ../../library/curses.rst:1295 msgid "" "Pretend the whole window has been changed, for purposes of drawing " "optimizations." msgstr "" -#: ../../library/curses.rst:1299 +#: ../../library/curses.rst:1301 msgid "" "Mark all lines in the window as unchanged since the last call to :meth:" "`refresh`." msgstr "" -#: ../../library/curses.rst:1306 +#: ../../library/curses.rst:1308 msgid "" "Display a vertical line starting at ``(y, x)`` with length *n* consisting of " "the character *ch* with attributes *attr*." msgstr "" -#: ../../library/curses.rst:1311 +#: ../../library/curses.rst:1313 msgid "Constants" msgstr "Constantes" -#: ../../library/curses.rst:1313 +#: ../../library/curses.rst:1315 msgid "The :mod:`curses` module defines the following data members:" msgstr "" -#: ../../library/curses.rst:1318 +#: ../../library/curses.rst:1320 msgid "" "Some curses routines that return an integer, such as :meth:`~window." "getch`, return :const:`ERR` upon failure." msgstr "" -#: ../../library/curses.rst:1324 +#: ../../library/curses.rst:1326 msgid "" "Some curses routines that return an integer, such as :func:`napms`, " "return :const:`OK` upon success." msgstr "" -#: ../../library/curses.rst:1331 +#: ../../library/curses.rst:1332 msgid "A bytes object representing the current version of the module." msgstr "" -#: ../../library/curses.rst:1336 +#: ../../library/curses.rst:1337 msgid "" "A named tuple containing the three components of the ncurses library " "version: *major*, *minor*, and *patch*. All values are integers. The " @@ -1526,536 +1513,536 @@ msgid "" "is equivalent to ``curses.ncurses_version.major`` and so on." msgstr "" -#: ../../library/curses.rst:1341 +#: ../../library/curses.rst:1342 msgid "Availability: if the ncurses library is used." msgstr "" -#: ../../library/curses.rst:1347 +#: ../../library/curses.rst:1348 msgid "" "The maximum number of colors the terminal can support. It is defined only " "after the call to :func:`start_color`." msgstr "" -#: ../../library/curses.rst:1352 +#: ../../library/curses.rst:1353 msgid "" "The maximum number of color pairs the terminal can support. It is defined " "only after the call to :func:`start_color`." msgstr "" -#: ../../library/curses.rst:1357 +#: ../../library/curses.rst:1358 msgid "" "The width of the screen, i.e., the number of columns. It is defined only " "after the call to :func:`initscr`. Updated by :func:`update_lines_cols`, :" "func:`resizeterm` and :func:`resize_term`." msgstr "" -#: ../../library/curses.rst:1364 +#: ../../library/curses.rst:1365 msgid "" "The height of the screen, i.e., the number of lines. It is defined only " "after the call to :func:`initscr`. Updated by :func:`update_lines_cols`, :" "func:`resizeterm` and :func:`resize_term`." msgstr "" -#: ../../library/curses.rst:1370 +#: ../../library/curses.rst:1371 msgid "" "Some constants are available to specify character cell attributes. The exact " "constants available are system dependent." msgstr "" -#: ../../library/curses.rst:1374 +#: ../../library/curses.rst:1375 msgid "Attribute" msgstr "Atributo" -#: ../../library/curses.rst:1374 ../../library/curses.rst:1419 -#: ../../library/curses.rst:1665 ../../library/curses.rst:1757 +#: ../../library/curses.rst:1375 ../../library/curses.rst:1420 +#: ../../library/curses.rst:1666 ../../library/curses.rst:1758 msgid "Meaning" msgstr "Significado" -#: ../../library/curses.rst:1376 +#: ../../library/curses.rst:1377 msgid "Alternate character set mode" msgstr "" -#: ../../library/curses.rst:1378 +#: ../../library/curses.rst:1379 msgid "Blink mode" msgstr "" -#: ../../library/curses.rst:1380 +#: ../../library/curses.rst:1381 msgid "Bold mode" msgstr "" -#: ../../library/curses.rst:1382 +#: ../../library/curses.rst:1383 msgid "Dim mode" msgstr "" -#: ../../library/curses.rst:1384 +#: ../../library/curses.rst:1385 msgid "Invisible or blank mode" msgstr "" -#: ../../library/curses.rst:1386 +#: ../../library/curses.rst:1387 msgid "Italic mode" msgstr "" -#: ../../library/curses.rst:1388 +#: ../../library/curses.rst:1389 msgid "Normal attribute" msgstr "" -#: ../../library/curses.rst:1390 +#: ../../library/curses.rst:1391 msgid "Protected mode" msgstr "" -#: ../../library/curses.rst:1392 +#: ../../library/curses.rst:1393 msgid "Reverse background and foreground colors" msgstr "" -#: ../../library/curses.rst:1395 +#: ../../library/curses.rst:1396 msgid "Standout mode" msgstr "" -#: ../../library/curses.rst:1397 +#: ../../library/curses.rst:1398 msgid "Underline mode" msgstr "" -#: ../../library/curses.rst:1399 +#: ../../library/curses.rst:1400 msgid "Horizontal highlight" msgstr "" -#: ../../library/curses.rst:1401 +#: ../../library/curses.rst:1402 msgid "Left highlight" msgstr "" -#: ../../library/curses.rst:1403 +#: ../../library/curses.rst:1404 msgid "Low highlight" msgstr "" -#: ../../library/curses.rst:1405 +#: ../../library/curses.rst:1406 msgid "Right highlight" msgstr "" -#: ../../library/curses.rst:1407 +#: ../../library/curses.rst:1408 msgid "Top highlight" msgstr "" -#: ../../library/curses.rst:1409 +#: ../../library/curses.rst:1410 msgid "Vertical highlight" msgstr "" -#: ../../library/curses.rst:1412 +#: ../../library/curses.rst:1413 msgid "``A_ITALIC`` was added." msgstr "" -#: ../../library/curses.rst:1415 +#: ../../library/curses.rst:1416 msgid "" "Several constants are available to extract corresponding attributes returned " "by some methods." msgstr "" -#: ../../library/curses.rst:1419 +#: ../../library/curses.rst:1420 msgid "Bit-mask" msgstr "" -#: ../../library/curses.rst:1421 +#: ../../library/curses.rst:1422 msgid "Bit-mask to extract attributes" msgstr "" -#: ../../library/curses.rst:1424 +#: ../../library/curses.rst:1425 msgid "Bit-mask to extract a character" msgstr "" -#: ../../library/curses.rst:1427 +#: ../../library/curses.rst:1428 msgid "Bit-mask to extract color-pair field information" msgstr "" -#: ../../library/curses.rst:1431 +#: ../../library/curses.rst:1432 msgid "" "Keys are referred to by integer constants with names starting with " "``KEY_``. The exact keycaps available are system dependent." msgstr "" -#: ../../library/curses.rst:1437 +#: ../../library/curses.rst:1438 msgid "Key constant" msgstr "" -#: ../../library/curses.rst:1437 +#: ../../library/curses.rst:1438 msgid "Key" msgstr "Chave" -#: ../../library/curses.rst:1439 +#: ../../library/curses.rst:1440 msgid "Minimum key value" msgstr "" -#: ../../library/curses.rst:1441 +#: ../../library/curses.rst:1442 msgid "Break key (unreliable)" msgstr "" -#: ../../library/curses.rst:1443 +#: ../../library/curses.rst:1444 msgid "Down-arrow" msgstr "" -#: ../../library/curses.rst:1445 +#: ../../library/curses.rst:1446 msgid "Up-arrow" msgstr "" -#: ../../library/curses.rst:1447 +#: ../../library/curses.rst:1448 msgid "Left-arrow" msgstr "" -#: ../../library/curses.rst:1449 +#: ../../library/curses.rst:1450 msgid "Right-arrow" msgstr "" -#: ../../library/curses.rst:1451 +#: ../../library/curses.rst:1452 msgid "Home key (upward+left arrow)" msgstr "" -#: ../../library/curses.rst:1453 +#: ../../library/curses.rst:1454 msgid "Backspace (unreliable)" msgstr "" -#: ../../library/curses.rst:1455 +#: ../../library/curses.rst:1456 msgid "Function keys. Up to 64 function keys are supported." msgstr "" -#: ../../library/curses.rst:1458 +#: ../../library/curses.rst:1459 msgid "Value of function key *n*" msgstr "" -#: ../../library/curses.rst:1460 +#: ../../library/curses.rst:1461 msgid "Delete line" msgstr "" -#: ../../library/curses.rst:1462 +#: ../../library/curses.rst:1463 msgid "Insert line" msgstr "" -#: ../../library/curses.rst:1464 +#: ../../library/curses.rst:1465 msgid "Delete character" msgstr "" -#: ../../library/curses.rst:1466 +#: ../../library/curses.rst:1467 msgid "Insert char or enter insert mode" msgstr "" -#: ../../library/curses.rst:1468 +#: ../../library/curses.rst:1469 msgid "Exit insert char mode" msgstr "" -#: ../../library/curses.rst:1470 +#: ../../library/curses.rst:1471 msgid "Clear screen" msgstr "" -#: ../../library/curses.rst:1472 +#: ../../library/curses.rst:1473 msgid "Clear to end of screen" msgstr "" -#: ../../library/curses.rst:1474 +#: ../../library/curses.rst:1475 msgid "Clear to end of line" msgstr "" -#: ../../library/curses.rst:1476 +#: ../../library/curses.rst:1477 msgid "Scroll 1 line forward" msgstr "" -#: ../../library/curses.rst:1478 +#: ../../library/curses.rst:1479 msgid "Scroll 1 line backward (reverse)" msgstr "" -#: ../../library/curses.rst:1480 +#: ../../library/curses.rst:1481 msgid "Next page" msgstr "" -#: ../../library/curses.rst:1482 +#: ../../library/curses.rst:1483 msgid "Previous page" msgstr "" -#: ../../library/curses.rst:1484 +#: ../../library/curses.rst:1485 msgid "Set tab" msgstr "" -#: ../../library/curses.rst:1486 +#: ../../library/curses.rst:1487 msgid "Clear tab" msgstr "" -#: ../../library/curses.rst:1488 +#: ../../library/curses.rst:1489 msgid "Clear all tabs" msgstr "" -#: ../../library/curses.rst:1490 +#: ../../library/curses.rst:1491 msgid "Enter or send (unreliable)" msgstr "" -#: ../../library/curses.rst:1492 +#: ../../library/curses.rst:1493 msgid "Soft (partial) reset (unreliable)" msgstr "" -#: ../../library/curses.rst:1494 +#: ../../library/curses.rst:1495 msgid "Reset or hard reset (unreliable)" msgstr "" -#: ../../library/curses.rst:1496 +#: ../../library/curses.rst:1497 msgid "Print" msgstr "" -#: ../../library/curses.rst:1498 +#: ../../library/curses.rst:1499 msgid "Home down or bottom (lower left)" msgstr "" -#: ../../library/curses.rst:1500 +#: ../../library/curses.rst:1501 msgid "Upper left of keypad" msgstr "" -#: ../../library/curses.rst:1502 +#: ../../library/curses.rst:1503 msgid "Upper right of keypad" msgstr "" -#: ../../library/curses.rst:1504 +#: ../../library/curses.rst:1505 msgid "Center of keypad" msgstr "" -#: ../../library/curses.rst:1506 +#: ../../library/curses.rst:1507 msgid "Lower left of keypad" msgstr "" -#: ../../library/curses.rst:1508 +#: ../../library/curses.rst:1509 msgid "Lower right of keypad" msgstr "" -#: ../../library/curses.rst:1510 +#: ../../library/curses.rst:1511 msgid "Back tab" msgstr "" -#: ../../library/curses.rst:1512 +#: ../../library/curses.rst:1513 msgid "Beg (beginning)" msgstr "" -#: ../../library/curses.rst:1514 +#: ../../library/curses.rst:1515 msgid "Cancel" -msgstr "" +msgstr "Cancelar" -#: ../../library/curses.rst:1516 +#: ../../library/curses.rst:1517 msgid "Close" msgstr "" -#: ../../library/curses.rst:1518 +#: ../../library/curses.rst:1519 msgid "Cmd (command)" msgstr "" -#: ../../library/curses.rst:1520 +#: ../../library/curses.rst:1521 msgid "Copy" msgstr "" -#: ../../library/curses.rst:1522 +#: ../../library/curses.rst:1523 msgid "Create" msgstr "" -#: ../../library/curses.rst:1524 +#: ../../library/curses.rst:1525 msgid "End" msgstr "" -#: ../../library/curses.rst:1526 +#: ../../library/curses.rst:1527 msgid "Exit" msgstr "" -#: ../../library/curses.rst:1528 +#: ../../library/curses.rst:1529 msgid "Find" msgstr "" -#: ../../library/curses.rst:1530 +#: ../../library/curses.rst:1531 msgid "Help" msgstr "" -#: ../../library/curses.rst:1532 +#: ../../library/curses.rst:1533 msgid "Mark" msgstr "" -#: ../../library/curses.rst:1534 +#: ../../library/curses.rst:1535 msgid "Message" msgstr "" -#: ../../library/curses.rst:1536 +#: ../../library/curses.rst:1537 msgid "Move" msgstr "" -#: ../../library/curses.rst:1538 +#: ../../library/curses.rst:1539 msgid "Next" msgstr "" -#: ../../library/curses.rst:1540 +#: ../../library/curses.rst:1541 msgid "Open" msgstr "" -#: ../../library/curses.rst:1542 +#: ../../library/curses.rst:1543 msgid "Options" msgstr "Opções" -#: ../../library/curses.rst:1544 +#: ../../library/curses.rst:1545 msgid "Prev (previous)" msgstr "" -#: ../../library/curses.rst:1546 +#: ../../library/curses.rst:1547 msgid "Redo" msgstr "" -#: ../../library/curses.rst:1548 +#: ../../library/curses.rst:1549 msgid "Ref (reference)" msgstr "" -#: ../../library/curses.rst:1550 +#: ../../library/curses.rst:1551 msgid "Refresh" msgstr "" -#: ../../library/curses.rst:1552 +#: ../../library/curses.rst:1553 msgid "Replace" msgstr "" -#: ../../library/curses.rst:1554 +#: ../../library/curses.rst:1555 msgid "Restart" msgstr "" -#: ../../library/curses.rst:1556 +#: ../../library/curses.rst:1557 msgid "Resume" msgstr "" -#: ../../library/curses.rst:1558 +#: ../../library/curses.rst:1559 msgid "Save" msgstr "Salvar" -#: ../../library/curses.rst:1560 +#: ../../library/curses.rst:1561 msgid "Shifted Beg (beginning)" msgstr "" -#: ../../library/curses.rst:1562 +#: ../../library/curses.rst:1563 msgid "Shifted Cancel" msgstr "" -#: ../../library/curses.rst:1564 +#: ../../library/curses.rst:1565 msgid "Shifted Command" msgstr "" -#: ../../library/curses.rst:1566 +#: ../../library/curses.rst:1567 msgid "Shifted Copy" msgstr "" -#: ../../library/curses.rst:1568 +#: ../../library/curses.rst:1569 msgid "Shifted Create" msgstr "" -#: ../../library/curses.rst:1570 +#: ../../library/curses.rst:1571 msgid "Shifted Delete char" msgstr "" -#: ../../library/curses.rst:1572 +#: ../../library/curses.rst:1573 msgid "Shifted Delete line" msgstr "" -#: ../../library/curses.rst:1574 +#: ../../library/curses.rst:1575 msgid "Select" msgstr "" -#: ../../library/curses.rst:1576 +#: ../../library/curses.rst:1577 msgid "Shifted End" msgstr "" -#: ../../library/curses.rst:1578 +#: ../../library/curses.rst:1579 msgid "Shifted Clear line" msgstr "" -#: ../../library/curses.rst:1580 +#: ../../library/curses.rst:1581 msgid "Shifted Exit" msgstr "" -#: ../../library/curses.rst:1582 +#: ../../library/curses.rst:1583 msgid "Shifted Find" msgstr "" -#: ../../library/curses.rst:1584 +#: ../../library/curses.rst:1585 msgid "Shifted Help" msgstr "" -#: ../../library/curses.rst:1586 +#: ../../library/curses.rst:1587 msgid "Shifted Home" msgstr "" -#: ../../library/curses.rst:1588 +#: ../../library/curses.rst:1589 msgid "Shifted Input" msgstr "" -#: ../../library/curses.rst:1590 +#: ../../library/curses.rst:1591 msgid "Shifted Left arrow" msgstr "" -#: ../../library/curses.rst:1592 +#: ../../library/curses.rst:1593 msgid "Shifted Message" msgstr "" -#: ../../library/curses.rst:1594 +#: ../../library/curses.rst:1595 msgid "Shifted Move" msgstr "" -#: ../../library/curses.rst:1596 +#: ../../library/curses.rst:1597 msgid "Shifted Next" msgstr "" -#: ../../library/curses.rst:1598 +#: ../../library/curses.rst:1599 msgid "Shifted Options" msgstr "" -#: ../../library/curses.rst:1600 +#: ../../library/curses.rst:1601 msgid "Shifted Prev" msgstr "" -#: ../../library/curses.rst:1602 +#: ../../library/curses.rst:1603 msgid "Shifted Print" msgstr "" -#: ../../library/curses.rst:1604 +#: ../../library/curses.rst:1605 msgid "Shifted Redo" msgstr "" -#: ../../library/curses.rst:1606 +#: ../../library/curses.rst:1607 msgid "Shifted Replace" msgstr "" -#: ../../library/curses.rst:1608 +#: ../../library/curses.rst:1609 msgid "Shifted Right arrow" msgstr "" -#: ../../library/curses.rst:1610 +#: ../../library/curses.rst:1611 msgid "Shifted Resume" msgstr "Resumo alterado" -#: ../../library/curses.rst:1612 +#: ../../library/curses.rst:1613 msgid "Shifted Save" msgstr "" -#: ../../library/curses.rst:1614 +#: ../../library/curses.rst:1615 msgid "Shifted Suspend" msgstr "" -#: ../../library/curses.rst:1616 +#: ../../library/curses.rst:1617 msgid "Shifted Undo" msgstr "" -#: ../../library/curses.rst:1618 +#: ../../library/curses.rst:1619 msgid "Suspend" msgstr "" -#: ../../library/curses.rst:1620 +#: ../../library/curses.rst:1621 msgid "Undo" msgstr "Desfazer" -#: ../../library/curses.rst:1622 +#: ../../library/curses.rst:1623 msgid "Mouse event has occurred" msgstr "" -#: ../../library/curses.rst:1624 +#: ../../library/curses.rst:1625 msgid "Terminal resize event" msgstr "" -#: ../../library/curses.rst:1626 +#: ../../library/curses.rst:1627 msgid "Maximum key value" msgstr "" -#: ../../library/curses.rst:1629 +#: ../../library/curses.rst:1630 msgid "" "On VT100s and their software emulations, such as X terminal emulators, there " "are normally at least four function keys (:const:`KEY_F1 `, :const:" @@ -2067,64 +2054,64 @@ msgid "" "keypad mappings are standard:" msgstr "" -#: ../../library/curses.rst:1638 +#: ../../library/curses.rst:1639 msgid "Keycap" msgstr "" -#: ../../library/curses.rst:1638 ../../library/curses.rst:1783 -#: ../../library/curses.rst:1907 +#: ../../library/curses.rst:1639 ../../library/curses.rst:1784 +#: ../../library/curses.rst:1908 msgid "Constant" msgstr "Constante" -#: ../../library/curses.rst:1640 +#: ../../library/curses.rst:1641 msgid ":kbd:`Insert`" msgstr ":kbd:`Insert`" -#: ../../library/curses.rst:1640 +#: ../../library/curses.rst:1641 msgid "KEY_IC" msgstr "KEY_IC" -#: ../../library/curses.rst:1642 +#: ../../library/curses.rst:1643 msgid ":kbd:`Delete`" msgstr ":kbd:`Delete`" -#: ../../library/curses.rst:1642 +#: ../../library/curses.rst:1643 msgid "KEY_DC" msgstr "KEY_DC" -#: ../../library/curses.rst:1644 +#: ../../library/curses.rst:1645 msgid ":kbd:`Home`" msgstr ":kbd:`Home`" -#: ../../library/curses.rst:1644 +#: ../../library/curses.rst:1645 msgid "KEY_HOME" msgstr "KEY_HOME" -#: ../../library/curses.rst:1646 +#: ../../library/curses.rst:1647 msgid ":kbd:`End`" msgstr ":kbd:`End`" -#: ../../library/curses.rst:1646 +#: ../../library/curses.rst:1647 msgid "KEY_END" msgstr "KEY_END" -#: ../../library/curses.rst:1648 +#: ../../library/curses.rst:1649 msgid ":kbd:`Page Up`" msgstr ":kbd:`Page Up`" -#: ../../library/curses.rst:1648 +#: ../../library/curses.rst:1649 msgid "KEY_PPAGE" msgstr "KEY_PPAGE" -#: ../../library/curses.rst:1650 +#: ../../library/curses.rst:1651 msgid ":kbd:`Page Down`" msgstr ":kbd:`Page Down`" -#: ../../library/curses.rst:1650 +#: ../../library/curses.rst:1651 msgid "KEY_NPAGE" msgstr "KEY_NPAGE" -#: ../../library/curses.rst:1655 +#: ../../library/curses.rst:1656 msgid "" "The following table lists characters from the alternate character set. These " "are inherited from the VT100 terminal, and will generally be available on " @@ -2132,268 +2119,268 @@ msgid "" "available, curses falls back on a crude printable ASCII approximation." msgstr "" -#: ../../library/curses.rst:1662 +#: ../../library/curses.rst:1663 msgid "These are available only after :func:`initscr` has been called." msgstr "" -#: ../../library/curses.rst:1665 +#: ../../library/curses.rst:1666 msgid "ACS code" msgstr "Código ACS" -#: ../../library/curses.rst:1667 +#: ../../library/curses.rst:1668 msgid "alternate name for upper right corner" msgstr "" -#: ../../library/curses.rst:1669 +#: ../../library/curses.rst:1670 msgid "solid square block" msgstr "" -#: ../../library/curses.rst:1671 +#: ../../library/curses.rst:1672 msgid "board of squares" msgstr "" -#: ../../library/curses.rst:1673 +#: ../../library/curses.rst:1674 msgid "alternate name for horizontal line" msgstr "" -#: ../../library/curses.rst:1675 +#: ../../library/curses.rst:1676 msgid "alternate name for upper left corner" msgstr "" -#: ../../library/curses.rst:1677 +#: ../../library/curses.rst:1678 msgid "alternate name for top tee" msgstr "" -#: ../../library/curses.rst:1679 +#: ../../library/curses.rst:1680 msgid "bottom tee" msgstr "" -#: ../../library/curses.rst:1681 +#: ../../library/curses.rst:1682 msgid "bullet" msgstr "" -#: ../../library/curses.rst:1683 +#: ../../library/curses.rst:1684 msgid "checker board (stipple)" msgstr "" -#: ../../library/curses.rst:1685 +#: ../../library/curses.rst:1686 msgid "arrow pointing down" msgstr "" -#: ../../library/curses.rst:1687 +#: ../../library/curses.rst:1688 msgid "degree symbol" msgstr "" -#: ../../library/curses.rst:1689 +#: ../../library/curses.rst:1690 msgid "diamond" msgstr "" -#: ../../library/curses.rst:1691 +#: ../../library/curses.rst:1692 msgid "greater-than-or-equal-to" msgstr "" -#: ../../library/curses.rst:1693 +#: ../../library/curses.rst:1694 msgid "horizontal line" msgstr "" -#: ../../library/curses.rst:1695 +#: ../../library/curses.rst:1696 msgid "lantern symbol" msgstr "" -#: ../../library/curses.rst:1697 +#: ../../library/curses.rst:1698 msgid "left arrow" msgstr "" -#: ../../library/curses.rst:1699 +#: ../../library/curses.rst:1700 msgid "less-than-or-equal-to" msgstr "" -#: ../../library/curses.rst:1701 +#: ../../library/curses.rst:1702 msgid "lower left-hand corner" msgstr "" -#: ../../library/curses.rst:1703 +#: ../../library/curses.rst:1704 msgid "lower right-hand corner" msgstr "" -#: ../../library/curses.rst:1705 +#: ../../library/curses.rst:1706 msgid "left tee" msgstr "" -#: ../../library/curses.rst:1707 +#: ../../library/curses.rst:1708 msgid "not-equal sign" msgstr "" -#: ../../library/curses.rst:1709 +#: ../../library/curses.rst:1710 msgid "letter pi" msgstr "" -#: ../../library/curses.rst:1711 +#: ../../library/curses.rst:1712 msgid "plus-or-minus sign" msgstr "" -#: ../../library/curses.rst:1713 +#: ../../library/curses.rst:1714 msgid "big plus sign" msgstr "" -#: ../../library/curses.rst:1715 +#: ../../library/curses.rst:1716 msgid "right arrow" msgstr "" -#: ../../library/curses.rst:1717 +#: ../../library/curses.rst:1718 msgid "right tee" msgstr "" -#: ../../library/curses.rst:1719 +#: ../../library/curses.rst:1720 msgid "scan line 1" msgstr "" -#: ../../library/curses.rst:1721 +#: ../../library/curses.rst:1722 msgid "scan line 3" msgstr "" -#: ../../library/curses.rst:1723 +#: ../../library/curses.rst:1724 msgid "scan line 7" msgstr "" -#: ../../library/curses.rst:1725 +#: ../../library/curses.rst:1726 msgid "scan line 9" msgstr "" -#: ../../library/curses.rst:1727 +#: ../../library/curses.rst:1728 msgid "alternate name for lower right corner" msgstr "" -#: ../../library/curses.rst:1729 +#: ../../library/curses.rst:1730 msgid "alternate name for vertical line" msgstr "" -#: ../../library/curses.rst:1731 +#: ../../library/curses.rst:1732 msgid "alternate name for right tee" msgstr "" -#: ../../library/curses.rst:1733 +#: ../../library/curses.rst:1734 msgid "alternate name for lower left corner" msgstr "" -#: ../../library/curses.rst:1735 +#: ../../library/curses.rst:1736 msgid "alternate name for bottom tee" msgstr "" -#: ../../library/curses.rst:1737 +#: ../../library/curses.rst:1738 msgid "alternate name for left tee" msgstr "" -#: ../../library/curses.rst:1739 +#: ../../library/curses.rst:1740 msgid "alternate name for crossover or big plus" msgstr "" -#: ../../library/curses.rst:1741 +#: ../../library/curses.rst:1742 msgid "pound sterling" msgstr "" -#: ../../library/curses.rst:1743 +#: ../../library/curses.rst:1744 msgid "top tee" msgstr "" -#: ../../library/curses.rst:1745 +#: ../../library/curses.rst:1746 msgid "up arrow" msgstr "" -#: ../../library/curses.rst:1747 +#: ../../library/curses.rst:1748 msgid "upper left corner" msgstr "" -#: ../../library/curses.rst:1749 +#: ../../library/curses.rst:1750 msgid "upper right corner" msgstr "" -#: ../../library/curses.rst:1751 +#: ../../library/curses.rst:1752 msgid "vertical line" msgstr "" -#: ../../library/curses.rst:1754 +#: ../../library/curses.rst:1755 msgid "" "The following table lists mouse button constants used by :meth:`getmouse`:" msgstr "" -#: ../../library/curses.rst:1757 +#: ../../library/curses.rst:1758 msgid "Mouse button constant" msgstr "" -#: ../../library/curses.rst:1759 +#: ../../library/curses.rst:1760 msgid "Mouse button *n* pressed" msgstr "" -#: ../../library/curses.rst:1761 +#: ../../library/curses.rst:1762 msgid "Mouse button *n* released" msgstr "" -#: ../../library/curses.rst:1763 +#: ../../library/curses.rst:1764 msgid "Mouse button *n* clicked" msgstr "" -#: ../../library/curses.rst:1765 +#: ../../library/curses.rst:1766 msgid "Mouse button *n* double clicked" msgstr "" -#: ../../library/curses.rst:1767 +#: ../../library/curses.rst:1768 msgid "Mouse button *n* triple clicked" msgstr "" -#: ../../library/curses.rst:1769 +#: ../../library/curses.rst:1770 msgid "Shift was down during button state change" msgstr "" -#: ../../library/curses.rst:1771 ../../library/curses.rst:1773 +#: ../../library/curses.rst:1772 ../../library/curses.rst:1774 msgid "Control was down during button state change" msgstr "" -#: ../../library/curses.rst:1780 +#: ../../library/curses.rst:1781 msgid "The following table lists the predefined colors:" msgstr "" -#: ../../library/curses.rst:1783 +#: ../../library/curses.rst:1784 msgid "Color" msgstr "" -#: ../../library/curses.rst:1785 +#: ../../library/curses.rst:1786 msgid "Black" msgstr "" -#: ../../library/curses.rst:1787 +#: ../../library/curses.rst:1788 msgid "Blue" msgstr "" -#: ../../library/curses.rst:1789 +#: ../../library/curses.rst:1790 msgid "Cyan (light greenish blue)" msgstr "" -#: ../../library/curses.rst:1791 +#: ../../library/curses.rst:1792 msgid "Green" msgstr "" -#: ../../library/curses.rst:1793 +#: ../../library/curses.rst:1794 msgid "Magenta (purplish red)" msgstr "" -#: ../../library/curses.rst:1795 +#: ../../library/curses.rst:1796 msgid "Red" msgstr "" -#: ../../library/curses.rst:1797 +#: ../../library/curses.rst:1798 msgid "White" msgstr "" -#: ../../library/curses.rst:1799 +#: ../../library/curses.rst:1800 msgid "Yellow" msgstr "" -#: ../../library/curses.rst:1804 +#: ../../library/curses.rst:1805 msgid ":mod:`curses.textpad` --- Text input widget for curses programs" msgstr "" -#: ../../library/curses.rst:1812 +#: ../../library/curses.rst:1813 msgid "" "The :mod:`curses.textpad` module provides a :class:`Textbox` class that " "handles elementary text editing in a curses window, supporting a set of " @@ -2403,11 +2390,11 @@ msgid "" "purposes." msgstr "" -#: ../../library/curses.rst:1818 +#: ../../library/curses.rst:1819 msgid "The module :mod:`curses.textpad` defines the following function:" msgstr "" -#: ../../library/curses.rst:1823 +#: ../../library/curses.rst:1824 msgid "" "Draw a rectangle. The first argument must be a window object; the remaining " "arguments are coordinates relative to that window. The second and third " @@ -2419,15 +2406,15 @@ msgid "" "will be drawn with ASCII dashes, vertical bars, and plus signs." msgstr "" -#: ../../library/curses.rst:1836 +#: ../../library/curses.rst:1837 msgid "Textbox objects" msgstr "" -#: ../../library/curses.rst:1838 +#: ../../library/curses.rst:1839 msgid "You can instantiate a :class:`Textbox` object as follows:" msgstr "" -#: ../../library/curses.rst:1843 +#: ../../library/curses.rst:1844 msgid "" "Return a textbox widget object. The *win* argument should be a curses :ref:" "`window ` object in which the textbox is to be " @@ -2436,11 +2423,11 @@ msgid "" "instance's :attr:`stripspaces` flag is initially on." msgstr "" -#: ../../library/curses.rst:1849 +#: ../../library/curses.rst:1850 msgid ":class:`Textbox` objects have the following methods:" msgstr "" -#: ../../library/curses.rst:1854 +#: ../../library/curses.rst:1855 msgid "" "This is the entry point you will normally use. It accepts editing " "keystrokes until one of the termination keystrokes is entered. If " @@ -2451,167 +2438,167 @@ msgid "" "`stripspaces` attribute." msgstr "" -#: ../../library/curses.rst:1865 +#: ../../library/curses.rst:1866 msgid "" "Process a single command keystroke. Here are the supported special " "keystrokes:" msgstr "" -#: ../../library/curses.rst:1869 ../../library/curses.rst:1907 +#: ../../library/curses.rst:1870 ../../library/curses.rst:1908 msgid "Keystroke" msgstr "" -#: ../../library/curses.rst:1869 +#: ../../library/curses.rst:1870 msgid "Action" msgstr "Ação" -#: ../../library/curses.rst:1871 +#: ../../library/curses.rst:1872 msgid ":kbd:`Control-A`" msgstr ":kbd:`Control-A`" -#: ../../library/curses.rst:1871 +#: ../../library/curses.rst:1872 msgid "Go to left edge of window." msgstr "" -#: ../../library/curses.rst:1873 ../../library/curses.rst:1909 +#: ../../library/curses.rst:1874 ../../library/curses.rst:1910 msgid ":kbd:`Control-B`" msgstr ":kbd:`Control-B`" -#: ../../library/curses.rst:1873 +#: ../../library/curses.rst:1874 msgid "Cursor left, wrapping to previous line if appropriate." msgstr "" -#: ../../library/curses.rst:1876 +#: ../../library/curses.rst:1877 msgid ":kbd:`Control-D`" msgstr ":kbd:`Control-D`" -#: ../../library/curses.rst:1876 +#: ../../library/curses.rst:1877 msgid "Delete character under cursor." msgstr "" -#: ../../library/curses.rst:1878 +#: ../../library/curses.rst:1879 msgid ":kbd:`Control-E`" msgstr ":kbd:`Control-E`" -#: ../../library/curses.rst:1878 +#: ../../library/curses.rst:1879 msgid "Go to right edge (stripspaces off) or end of line (stripspaces on)." msgstr "" -#: ../../library/curses.rst:1881 ../../library/curses.rst:1911 +#: ../../library/curses.rst:1882 ../../library/curses.rst:1912 msgid ":kbd:`Control-F`" msgstr ":kbd:`Control-F`" -#: ../../library/curses.rst:1881 +#: ../../library/curses.rst:1882 msgid "Cursor right, wrapping to next line when appropriate." msgstr "" -#: ../../library/curses.rst:1884 +#: ../../library/curses.rst:1885 msgid ":kbd:`Control-G`" msgstr ":kbd:`Control-G`" -#: ../../library/curses.rst:1884 +#: ../../library/curses.rst:1885 msgid "Terminate, returning the window contents." msgstr "" -#: ../../library/curses.rst:1886 +#: ../../library/curses.rst:1887 msgid ":kbd:`Control-H`" msgstr ":kbd:`Control-H`" -#: ../../library/curses.rst:1886 +#: ../../library/curses.rst:1887 msgid "Delete character backward." msgstr "" -#: ../../library/curses.rst:1888 +#: ../../library/curses.rst:1889 msgid ":kbd:`Control-J`" msgstr ":kbd:`Control-J`" -#: ../../library/curses.rst:1888 +#: ../../library/curses.rst:1889 msgid "Terminate if the window is 1 line, otherwise insert newline." msgstr "" -#: ../../library/curses.rst:1891 +#: ../../library/curses.rst:1892 msgid ":kbd:`Control-K`" msgstr ":kbd:`Control-K`" -#: ../../library/curses.rst:1891 +#: ../../library/curses.rst:1892 msgid "If line is blank, delete it, otherwise clear to end of line." msgstr "" -#: ../../library/curses.rst:1894 +#: ../../library/curses.rst:1895 msgid ":kbd:`Control-L`" msgstr ":kbd:`Control-L`" -#: ../../library/curses.rst:1894 +#: ../../library/curses.rst:1895 msgid "Refresh screen." msgstr "" -#: ../../library/curses.rst:1896 ../../library/curses.rst:1915 +#: ../../library/curses.rst:1897 ../../library/curses.rst:1916 msgid ":kbd:`Control-N`" msgstr ":kbd:`Control-N`" -#: ../../library/curses.rst:1896 +#: ../../library/curses.rst:1897 msgid "Cursor down; move down one line." msgstr "" -#: ../../library/curses.rst:1898 +#: ../../library/curses.rst:1899 msgid ":kbd:`Control-O`" msgstr ":kbd:`Control-O`" -#: ../../library/curses.rst:1898 +#: ../../library/curses.rst:1899 msgid "Insert a blank line at cursor location." msgstr "" -#: ../../library/curses.rst:1900 ../../library/curses.rst:1913 +#: ../../library/curses.rst:1901 ../../library/curses.rst:1914 msgid ":kbd:`Control-P`" msgstr ":kbd:`Control-P`" -#: ../../library/curses.rst:1900 +#: ../../library/curses.rst:1901 msgid "Cursor up; move up one line." msgstr "" -#: ../../library/curses.rst:1903 +#: ../../library/curses.rst:1904 msgid "" "Move operations do nothing if the cursor is at an edge where the movement is " "not possible. The following synonyms are supported where possible:" msgstr "" -#: ../../library/curses.rst:1909 +#: ../../library/curses.rst:1910 msgid ":const:`~curses.KEY_LEFT`" msgstr ":const:`~curses.KEY_LEFT`" -#: ../../library/curses.rst:1911 +#: ../../library/curses.rst:1912 msgid ":const:`~curses.KEY_RIGHT`" msgstr ":const:`~curses.KEY_RIGHT`" -#: ../../library/curses.rst:1913 +#: ../../library/curses.rst:1914 msgid ":const:`~curses.KEY_UP`" msgstr ":const:`~curses.KEY_UP`" -#: ../../library/curses.rst:1915 +#: ../../library/curses.rst:1916 msgid ":const:`~curses.KEY_DOWN`" msgstr ":const:`~curses.KEY_DOWN`" -#: ../../library/curses.rst:1917 +#: ../../library/curses.rst:1918 msgid ":const:`~curses.KEY_BACKSPACE`" msgstr ":const:`~curses.KEY_BACKSPACE`" -#: ../../library/curses.rst:1917 +#: ../../library/curses.rst:1918 msgid ":kbd:`Control-h`" msgstr ":kbd:`Control-h`" -#: ../../library/curses.rst:1920 +#: ../../library/curses.rst:1921 msgid "" "All other keystrokes are treated as a command to insert the given character " "and move right (with line wrapping)." msgstr "" -#: ../../library/curses.rst:1926 +#: ../../library/curses.rst:1927 msgid "" "Return the window contents as a string; whether blanks in the window are " "included is affected by the :attr:`stripspaces` member." msgstr "" -#: ../../library/curses.rst:1932 +#: ../../library/curses.rst:1933 msgid "" "This attribute is a flag which controls the interpretation of blanks in the " "window. When it is on, trailing blanks on each line are ignored; any cursor " diff --git a/library/custominterp.po b/library/custominterp.po index 2ccd372fe..408160e0a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..2cb9b13c6 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 +# python-doc bot, 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-10-07 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,50 @@ 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 "" +"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" + #: ../../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 "" +"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" + #: ../../library/dataclasses.rst:41 msgid "" "Note that this method is automatically added to the class: it is not " @@ -124,6 +159,36 @@ 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 "" +"@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" +" ..." + #: ../../library/dataclasses.rst:87 msgid "The parameters to ``@dataclass`` are:" msgstr "Os parâmetros do ``@dataclass`` são:" @@ -206,30 +271,34 @@ msgstr "" #: ../../library/dataclasses.rst:124 msgid "" -"*unsafe_hash*: If ``False`` (the default), a :meth:`~object.__hash__` method " -"is generated according to how *eq* and *frozen* are set." +"*unsafe_hash*: If true, force ``dataclasses`` to create a :meth:`~object." +"__hash__` method, even though it may not be safe to do so. Otherwise, " +"generate a :meth:`~object.__hash__` method according to how *eq* and " +"*frozen* are set. The default value is ``False``." msgstr "" -"*unsafe_hash*: Se ``False`` (o padrão), um método :meth:`~object.__hash__` é " -"gerado, conforme a forma como *eq* e *frozen* estão configurados." +"*unsafe_hash*: Se verdadeiro, força ``dataclasses`` a criar um método :meth:" +"`~object.__hash__`, mesmo que não seja seguro fazê-lo. Caso contrário, gera " +"um método :meth:`~object.__hash__` de acordo com a configuração de *eq* e " +"*frozen*. O valor padrão é ``False``." -#: ../../library/dataclasses.rst:127 +#: ../../library/dataclasses.rst:130 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. " +":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 +#: ../../library/dataclasses.rst:137 msgid "" "By default, ``@dataclass`` will not implicitly add a :meth:`~object." "__hash__` method unless it is safe to do so. Neither will it add or change " @@ -244,7 +313,7 @@ msgstr "" "específico para o Python, conforme descrito na documentação de :meth:`!" "__hash__`." -#: ../../library/dataclasses.rst:140 +#: ../../library/dataclasses.rst:143 msgid "" "If :meth:`!__hash__` is not explicitly defined, or if it is set to ``None``, " "then ``@dataclass`` *may* add an implicit :meth:`!__hash__` method. Although " @@ -260,7 +329,7 @@ msgstr "" "caso se sua classe é logicamente imutável, mas na prática pode ser mudada. " "Esse é um caso de uso específico e deve ser considerado com muito cuidado." -#: ../../library/dataclasses.rst:147 +#: ../../library/dataclasses.rst:150 msgid "" "Here are the rules governing implicit creation of a :meth:`!__hash__` " "method. Note that you cannot both have an explicit :meth:`!__hash__` method " @@ -272,7 +341,7 @@ msgstr "" "na dataclass e configurar ``unsafe_hash=True``; isso resultará em um :exc:" "`TypeError`." -#: ../../library/dataclasses.rst:152 +#: ../../library/dataclasses.rst:155 msgid "" "If *eq* and *frozen* are both true, by default ``@dataclass`` will generate " "a :meth:`!__hash__` method for you. If *eq* is true and *frozen* is false, :" @@ -290,63 +359,88 @@ msgstr "" "superclasse será usado (se a superclasse é :class:`object`, significa que " "voltará para o hash baseado em id)." -#: ../../library/dataclasses.rst:160 +#: ../../library/dataclasses.rst:163 msgid "" "*frozen*: If true (the default is ``False``), assigning to fields will " -"generate an exception. This emulates read-only frozen instances. If :meth:" -"`~object.__setattr__` or :meth:`~object.__delattr__` is defined in the " -"class, then :exc:`TypeError` is raised. See the discussion below." +"generate an exception. This emulates read-only frozen instances. See the :" +"ref:`discussion ` below." msgstr "" -"*frozen*: Se verdadeiro (o padrão é ``False``), atribuições para os campos " -"vão gerar uma exceção. Imita instâncias congeladas, somente leitura. Se :" -"meth:`~object.__setattr__` ou :meth:`~object.__delattr__` é definido na " -"classe, a exceção :exc:`TypeError` é levantada. Veja a discussão abaixo." -#: ../../library/dataclasses.rst:165 +#: ../../library/dataclasses.rst:167 +msgid "" +"If :meth:`~object.__setattr__` or :meth:`~object.__delattr__` is defined in " +"the class and *frozen* is true, then :exc:`TypeError` is raised." +msgstr "" + +#: ../../library/dataclasses.rst:170 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." +"__match_args__` será criada a partir da lista de parâmetros não-somente-" +"nomeado 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 +#: ../../library/dataclasses.rst:179 msgid "" "*kw_only*: If true (the default value is ``False``), then all fields will be " "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`." +"campo quando :meth:`!__init__` é chamado. Veja a entrada :term:`parâmetro` " +"do glossário para detalhes. Veja também a seção :const:`KW_ONLY`." + +#: ../../library/dataclasses.rst:187 +msgid "Keyword-only fields are not included in :attr:`!__match_args__`." +msgstr "Campos somente-nomeados não são incluídos em :attr:`!__match_args__`." -#: ../../library/dataclasses.rst:185 +#: ../../library/dataclasses.rst:191 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 "" +"*slots*: Se true (o padrão é ``False``), o atributo :attr:`~object." +"__slots__` será gerado e uma nova classe será retornada no lugar da " +"original. Se :attr:`!__slots__` já estiver definido na classe, então :exc:" +"`TypeError` será levantada." + +#: ../../library/dataclasses.rst:197 +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:195 +#: ../../library/dataclasses.rst:204 +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 "" +"Passar parâmetros para uma classe base :meth:`~object.__init_subclass__` ao " +"usar ``slots=True`` resultará em um :exc:`TypeError`. Use " +"``__init_subclass__`` sem parâmetros ou use valores padrão como solução " +"alternativa. Consulte :gh:`91126` para obter detalhes completos." + +#: ../../library/dataclasses.rst:212 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 " @@ -355,16 +449,26 @@ msgid "" "`fields` instead. To be able to determine inherited slots, base class :attr:" "`!__slots__` may be any iterable, but *not* an iterator." msgstr "" +"Se um nome de campo já estiver incluído no :attr:`!__slots__` de uma classe " +"base, ele não será incluído no :attr:`!__slots__` gerado para evitar :ref:" +"`substitui-los `. Portanto, não use :attr:`!__slots__` " +"para recuperar os nomes dos campos de uma classe de dados. Use :func:" +"`fields` em vez disso. Para poder determinar os slots herdados, a classe " +"base :attr:`!__slots__` pode ser qualquer iterável, mas *não* um iterador." -#: ../../library/dataclasses.rst:205 +#: ../../library/dataclasses.rst:222 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 "" +"*weakref_slot*: Se verdadeiro (o padrão é ``False``), adicione um slot " +"chamado \"__weakref__\", que é necessário para tornar uma instância :func:" +"`fraca `. É um erro especificar ``weakref_slot=True`` sem " +"também especificar ``slots=True``." -#: ../../library/dataclasses.rst:212 +#: ../../library/dataclasses.rst:230 msgid "" "``field``\\s may optionally specify a default value, using normal Python " "syntax::" @@ -372,13 +476,31 @@ msgstr "" "``field``\\s pode opcionalmente especificar um valor padrão, usando sintaxe " "Python normal::" -#: ../../library/dataclasses.rst:220 +#: ../../library/dataclasses.rst:233 +msgid "" +"@dataclass\n" +"class C:\n" +" a: int # 'a' has no default value\n" +" b: int = 0 # assign a default value for 'b'" +msgstr "" +"@dataclass\n" +"class C:\n" +" a: int # 'a' tem nenhum valor mínimo\n" +" b: int = 0 # atribui um valor padrão para 'b'" + +#: ../../library/dataclasses.rst:238 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 "" +"Nesse exemplo, :attr:`!a` e :attr:`!b` serão incluídos no método :meth:" +"`~object.__init__` adicionado, que será definido como::" + +#: ../../library/dataclasses.rst:241 +msgid "def __init__(self, a: int, b: int = 0):" +msgstr "def __init__(self, a: int, b: int = 0):" -#: ../../library/dataclasses.rst:225 +#: ../../library/dataclasses.rst:243 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 +510,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:249 msgid "" "For common and simple use cases, no other functionality is required. There " "are, however, some dataclass features that require additional per-field " @@ -396,8 +518,29 @@ msgid "" "replace the default field value with a call to the provided :func:`!field` " "function. For example::" msgstr "" +"Para casos de uso comuns e simples, nenhuma outra funcionalidade é " +"necessária. Existem, no entanto, alguns recursos que requerem informações " +"adicionais por campo. Para satisfazer essa necessidade de informações " +"adicionais, você pode substituir o valor do campo padrão por uma chamada " +"para a função :func:`!field` fornecida. Por exemplo::" + +#: ../../library/dataclasses.rst:255 +msgid "" +"@dataclass\n" +"class C:\n" +" mylist: list[int] = field(default_factory=list)\n" +"\n" +"c = C()\n" +"c.mylist += [1, 2, 3]" +msgstr "" +"@dataclass\n" +"class C:\n" +" mylist: list[int] = field(default_factory=list)\n" +"\n" +"c = C()\n" +"c.mylist += [1, 2, 3]" -#: ../../library/dataclasses.rst:244 +#: ../../library/dataclasses.rst:262 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 +553,21 @@ msgstr "" "com um significado distinto. Nenhum código deve usar diretamente o valor :" "const:`MISSING`." -#: ../../library/dataclasses.rst:249 +#: ../../library/dataclasses.rst:267 msgid "The parameters to :func:`!field` are:" -msgstr "" +msgstr "Os parâmetros de :func:`!field` são:" -#: ../../library/dataclasses.rst:251 +#: ../../library/dataclasses.rst:269 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 "" +"*default*: Se fornecido, este será o valor padrão para este campo. Isso é " +"necessário porque a própria chamada :func:`!field` substitui a posição " +"normal do valor padrão." -#: ../../library/dataclasses.rst:255 +#: ../../library/dataclasses.rst:273 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 " @@ -429,29 +575,46 @@ msgid "" "discussed below. It is an error to specify both *default* and " "*default_factory*." msgstr "" +"*default_factory*: Se fornecido, deve ser um chamável sem argumento que será " +"chamado quando um valor padrão for necessário para este campo. Entre outras " +"finalidades, isso pode ser usado para especificar campos com valores padrão " +"mutáveis, conforme discutido abaixo. É um erro especificar ambos *default* e " +"*default_factory*." -#: ../../library/dataclasses.rst:261 +#: ../../library/dataclasses.rst:279 msgid "" "*init*: If true (the default), this field is included as a parameter to the " "generated :meth:`~object.__init__` method." msgstr "" +"*init*: Se verdadeiro (o padrão), este campo é incluído como um parâmetro " +"para o método :meth:`~object.__init__` gerado." -#: ../../library/dataclasses.rst:264 +#: ../../library/dataclasses.rst:282 msgid "" "*repr*: If true (the default), this field is included in the string returned " "by the generated :meth:`~object.__repr__` method." msgstr "" +"*repr*: Se verdadeiro (o padrão), este campo é incluído na string retornada " +"pelo método :meth:`~object.__repr__` gerado." -#: ../../library/dataclasses.rst:267 +#: ../../library/dataclasses.rst:285 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." -msgstr "" - -#: ../../library/dataclasses.rst:274 +"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 "" +"*hash*: Pode ser um bool ou ``None``. Se verdadeiro, este campo é incluído " +"no método :meth:`~object.__hash__` gerado. Se false, este campo é excluído " +"do :meth:`~object.__hash__` gerado. Se ``None`` (o padrão), usa o valor de " +"*compare*: este seria normalmente o comportamento esperado, já que um campo " +"deve ser incluído no hash se for usado para comparações. Definir este valor " +"para algo diferente de ``None`` é desencorajado." + +#: ../../library/dataclasses.rst:293 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 +628,17 @@ 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:299 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 "" +"*compare*: Se verdadeiro (o padrão), este campo é incluído nos métodos de " +"igualdade e comparação gerados (:meth:`~object.__eq__`, :meth:`~object." +"__gt__`, etc.)." -#: ../../library/dataclasses.rst:284 +#: ../../library/dataclasses.rst:303 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 " @@ -481,32 +647,56 @@ msgid "" "mechanism. Multiple third-parties can each have their own key, to use as a " "namespace in the metadata." msgstr "" +"*metadata*: Pode ser um mapeamento ou ``None``. ``None`` é tratado como um " +"dicionário vazio. Este valor é agrupado em :func:`~types.MappingProxyType` " +"para torná-lo somente leitura e exposto no objeto :class:`Field`. Ele não é " +"usado por Data Classes e é fornecido como um mecanismo de extensão de " +"terceiros. Vários terceiros podem ter sua própria chave, para usar como um " +"espaço de nomes nos metadados." -#: ../../library/dataclasses.rst:292 +#: ../../library/dataclasses.rst:311 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 "" +"*kw_only*: Se verdadeiro, este campo será marcado como somente-nomeado. Isso " +"é usado quando os parâmetros do método :meth:`~object.__init__` gerados são " +"calculados." + +#: ../../library/dataclasses.rst:315 +msgid "Keyword-only fields are also not included in :attr:`!__match_args__`." +msgstr "" +"Campos somente-nomeados também não são incluídos em :attr:`!__match_args__`." -#: ../../library/dataclasses.rst:298 +#: ../../library/dataclasses.rst:319 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 " "*default* value. If *default* is not provided, then the class attribute " -"will be deleted. The intent is that after the :func:`@dataclass " -"` decorator runs, the class attributes will all contain the " -"default values for the fields, just as if the default value itself were " -"specified. For example, after::" +"will be deleted. The intent is that after the :deco:`dataclass` decorator " +"runs, the class attributes will all contain the default values for the " +"fields, just as if the default value itself were specified. For example, " +"after::" msgstr "" -#: ../../library/dataclasses.rst:314 +#: ../../library/dataclasses.rst:328 +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:335 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:341 msgid "" ":class:`!Field` objects describe each defined field. These objects are " "created internally, and are returned by the :func:`fields` module-level " @@ -514,22 +704,22 @@ msgid "" "directly. Its documented attributes are:" msgstr "" -#: ../../library/dataclasses.rst:325 +#: ../../library/dataclasses.rst:346 msgid ":attr:`!name`: The name of the field." msgstr "" -#: ../../library/dataclasses.rst:326 +#: ../../library/dataclasses.rst:347 msgid ":attr:`!type`: The type of the field." msgstr "" -#: ../../library/dataclasses.rst:327 +#: ../../library/dataclasses.rst:348 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:352 msgid "" "Other attributes may exist, but they are private and must not be inspected " "or relied on." @@ -537,7 +727,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:357 +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:366 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 +749,7 @@ msgstr "" "instância de uma. Não retorna pseudocampos que são ``ClassVar`` ou " "``InitVar``." -#: ../../library/dataclasses.rst:343 +#: ../../library/dataclasses.rst:373 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 +757,43 @@ msgid "" "into. Other objects are copied with :func:`copy.deepcopy`." msgstr "" -#: ../../library/dataclasses.rst:349 +#: ../../library/dataclasses.rst:379 msgid "Example of using :func:`!asdict` on nested dataclasses::" msgstr "" -#: ../../library/dataclasses.rst:366 ../../library/dataclasses.rst:386 +#: ../../library/dataclasses.rst:381 +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:396 ../../library/dataclasses.rst:416 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:398 +msgid "{field.name: getattr(obj, field.name) for field in fields(obj)}" +msgstr "" + +#: ../../library/dataclasses.rst:400 msgid "" ":func:`!asdict` raises :exc:`TypeError` if *obj* is not a dataclass instance." msgstr "" -#: ../../library/dataclasses.rst:375 +#: ../../library/dataclasses.rst:405 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 +801,27 @@ msgid "" "objects are copied with :func:`copy.deepcopy`." msgstr "" -#: ../../library/dataclasses.rst:381 +#: ../../library/dataclasses.rst:411 msgid "Continuing from the previous example::" msgstr "Continuando a partir do exemplo anterior::" -#: ../../library/dataclasses.rst:390 +#: ../../library/dataclasses.rst:413 +msgid "" +"assert astuple(p) == (10, 20)\n" +"assert astuple(c) == ([(0, 0), (10, 4)],)" +msgstr "" + +#: ../../library/dataclasses.rst:418 +msgid "tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))" +msgstr "" + +#: ../../library/dataclasses.rst:420 msgid "" ":func:`!astuple` raises :exc:`TypeError` if *obj* is not a dataclass " "instance." msgstr "" -#: ../../library/dataclasses.rst:395 +#: ../../library/dataclasses.rst:425 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 " @@ -598,29 +829,50 @@ msgid "" "``name``, ``(name, type)``, or ``(name, type, Field)``. If just ``name`` is " "supplied, :data:`typing.Any` is used for ``type``. The values of *init*, " "*repr*, *eq*, *order*, *unsafe_hash*, *frozen*, *match_args*, *kw_only*, " -"*slots*, and *weakref_slot* have the same meaning as they do in :func:" -"`@dataclass `." +"*slots*, and *weakref_slot* have the same meaning as they do in :deco:" +"`dataclass`." msgstr "" -#: ../../library/dataclasses.rst:405 +#: ../../library/dataclasses.rst:435 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:439 msgid "" "This function is not strictly required, because any Python mechanism for " -"creating a new class with :attr:`!__annotations__` can then apply the :func:" -"`@dataclass ` function to convert that class to a dataclass. " -"This function is provided as a convenience. For example::" +"creating a new class with :attr:`!__annotations__` can then apply the :deco:" +"`dataclass` function to convert that class to a dataclass. This function is " +"provided as a convenience. For example::" +msgstr "" + +#: ../../library/dataclasses.rst:445 +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:421 +#: ../../library/dataclasses.rst:451 msgid "Is equivalent to::" msgstr "É equivalente a::" -#: ../../library/dataclasses.rst:434 +#: ../../library/dataclasses.rst:453 +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:464 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 +880,27 @@ msgid "" "`TypeError`." msgstr "" -#: ../../library/dataclasses.rst:439 +#: ../../library/dataclasses.rst:469 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:473 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:477 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:481 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 +911,19 @@ msgid "" "instance copying." msgstr "" -#: ../../library/dataclasses.rst:460 +#: ../../library/dataclasses.rst:490 msgid "" "Dataclass instances are also supported by generic function :func:`copy." "replace`." msgstr "" -#: ../../library/dataclasses.rst:464 +#: ../../library/dataclasses.rst:494 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:497 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 +933,17 @@ msgstr "" "dataclass de fato), então adicione uma verificação para ``not " "isinstance(obj, type)``::" -#: ../../library/dataclasses.rst:476 +#: ../../library/dataclasses.rst:501 +msgid "" +"def is_dataclass_instance(obj):\n" +" return is_dataclass(obj) and not isinstance(obj, type)" +msgstr "" + +#: ../../library/dataclasses.rst:506 msgid "A sentinel value signifying a missing default or default_factory." msgstr "" -#: ../../library/dataclasses.rst:480 +#: ../../library/dataclasses.rst:510 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 +954,42 @@ msgid "" "the class is instantiated." msgstr "" -#: ../../library/dataclasses.rst:489 +#: ../../library/dataclasses.rst:519 msgid "" "In this example, the fields ``y`` and ``z`` will be marked as keyword-only " "fields::" msgstr "" -#: ../../library/dataclasses.rst:500 +#: ../../library/dataclasses.rst:521 +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:530 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:537 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:544 msgid "Post-init processing" msgstr "Processamento pós-inicialização" -#: ../../library/dataclasses.rst:518 +#: ../../library/dataclasses.rst:548 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,132 +999,189 @@ msgid "" "automatically be called." msgstr "" -#: ../../library/dataclasses.rst:525 +#: ../../library/dataclasses.rst:555 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:558 +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:567 msgid "" -"The :meth:`~object.__init__` method generated by :func:`@dataclass " -"` does not call base class :meth:`!__init__` methods. If the base " -"class has an :meth:`!__init__` method that has to be called, it is common to " -"call this method in a :meth:`__post_init__` method::" +"The :meth:`~object.__init__` method generated by :deco:`dataclass` does not " +"call base class :meth:`!__init__` methods. If the base class has an :meth:`!" +"__init__` method that has to be called, it is common to call this method in " +"a :meth:`__post_init__` method::" msgstr "" -#: ../../library/dataclasses.rst:554 +#: ../../library/dataclasses.rst:572 +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:584 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:588 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:595 msgid "Class variables" msgstr "Variáveis de classe" -#: ../../library/dataclasses.rst:567 +#: ../../library/dataclasses.rst:597 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 " -"defined in :pep:`526`. It does this by checking if the type of the field " -"is :data:`typing.ClassVar`. If a field is a ``ClassVar``, it is excluded " -"from consideration as a field and is ignored by the dataclass mechanisms. " -"Such ``ClassVar`` pseudo-fields are not returned by the module-level :func:" -"`fields` function." +"One of the few places where :deco:`dataclass` actually inspects the type of " +"a field is to determine if a field is a class variable as defined in :pep:" +"`526`. It does this by checking if the type of the field is :data:`typing." +"ClassVar`. If a field is a ``ClassVar``, it is excluded from consideration " +"as a field and is ignored by the dataclass mechanisms. Such ``ClassVar`` " +"pseudo-fields are not returned by the module-level :func:`fields` function." msgstr "" -#: ../../library/dataclasses.rst:578 +#: ../../library/dataclasses.rst:608 msgid "Init-only variables" msgstr "Variáveis de inicialização apenas" -#: ../../library/dataclasses.rst:580 +#: ../../library/dataclasses.rst:610 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-" -"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 " -"optional :meth:`__post_init__` method. They are not otherwise used by " -"dataclasses." +"Another place where :deco:`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 :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 optional :meth:" +"`__post_init__` method. They are not otherwise used by dataclasses." msgstr "" -#: ../../library/dataclasses.rst:590 +#: ../../library/dataclasses.rst:620 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:623 +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:635 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:641 msgid "Frozen instances" msgstr "" -#: ../../library/dataclasses.rst:613 +#: ../../library/dataclasses.rst:643 msgid "" "It is not possible to create truly immutable Python objects. However, by " -"passing ``frozen=True`` to the :func:`@dataclass ` decorator you " -"can emulate immutability. In that case, dataclasses will add :meth:`~object." +"passing ``frozen=True`` to the :deco:`dataclass` decorator you can emulate " +"immutability. In that case, dataclasses will add :meth:`~object." "__setattr__` and :meth:`~object.__delattr__` methods to the class. These " "methods will raise a :exc:`FrozenInstanceError` when invoked." msgstr "" -#: ../../library/dataclasses.rst:619 +#: ../../library/dataclasses.rst:649 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:658 msgid "Inheritance" msgstr "Herança" -#: ../../library/dataclasses.rst:630 +#: ../../library/dataclasses.rst:660 +msgid "" +"When the dataclass is being created by the :deco:`dataclass` decorator, it " +"looks through all of the class's base classes in reverse MRO (that is, " +"starting at :class:`object`) and, for each dataclass that it finds, adds the " +"fields from that base class to an ordered mapping of fields. After all of " +"the base class fields are added, it adds its own fields to the ordered " +"mapping. All of the generated methods will use this combined, calculated " +"ordered mapping of fields. Because the fields are in insertion order, " +"derived classes override base classes. An example::" +msgstr "" + +#: ../../library/dataclasses.rst:670 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 " -"(that is, starting at :class:`object`) and, for each dataclass that it " -"finds, adds the fields from that base class to an ordered mapping of fields. " -"After all of the base class fields are added, it adds its own fields to the " -"ordered mapping. All of the generated methods will use this combined, " -"calculated ordered mapping of fields. Because the fields are in insertion " -"order, derived classes override base classes. An example::" +"@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:650 +#: ../../library/dataclasses.rst:680 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:683 msgid "" "The generated :meth:`~object.__init__` method for :class:`!C` will look " "like::" msgstr "" -#: ../../library/dataclasses.rst:658 +#: ../../library/dataclasses.rst:685 +msgid "def __init__(self, x: int = 15, y: int = 0, z: int = 10):" +msgstr "" + +#: ../../library/dataclasses.rst:688 msgid "Re-ordering of keyword-only parameters in :meth:`!__init__`" msgstr "" -#: ../../library/dataclasses.rst:660 +#: ../../library/dataclasses.rst:690 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 +1189,67 @@ msgid "" "implemented in Python: they must come after non-keyword-only parameters." msgstr "" -#: ../../library/dataclasses.rst:666 +#: ../../library/dataclasses.rst:696 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:699 +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:711 msgid "The generated :meth:`!__init__` method for :class:`!D` will look like::" msgstr "" -#: ../../library/dataclasses.rst:685 +#: ../../library/dataclasses.rst:713 +msgid "" +"def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: " +"int = 0):" +msgstr "" + +#: ../../library/dataclasses.rst:715 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:719 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:724 msgid "Default factory functions" msgstr "Funções padrão de fábrica" -#: ../../library/dataclasses.rst:696 +#: ../../library/dataclasses.rst:726 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:730 +msgid "mylist: list = field(default_factory=list)" +msgstr "" + +#: ../../library/dataclasses.rst:732 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,91 +1258,165 @@ msgid "" "initial value." msgstr "" -#: ../../library/dataclasses.rst:709 +#: ../../library/dataclasses.rst:739 msgid "Mutable default values" msgstr "Valores padrão mutáveis" -#: ../../library/dataclasses.rst:711 +#: ../../library/dataclasses.rst:741 msgid "" "Python stores default member variable values in class attributes. Consider " "this example, not using dataclasses::" msgstr "" -#: ../../library/dataclasses.rst:726 +#: ../../library/dataclasses.rst:744 +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:756 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:759 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:761 +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:767 msgid "it would generate code similar to::" msgstr "Geraria código similar a::" -#: ../../library/dataclasses.rst:748 +#: ../../library/dataclasses.rst:769 +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:778 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 :" "attr:`!x` when creating a class instance will share the same copy of :attr:`!" "x`. Because dataclasses just use normal Python class creation they also " "share this behavior. There is no general way for Data Classes to detect " -"this condition. Instead, the :func:`@dataclass ` decorator will " -"raise a :exc:`ValueError` if it detects an unhashable default parameter. " -"The assumption is that if a value is unhashable, it is mutable. This is a " -"partial solution, but it does protect against many common errors." +"this condition. Instead, the :deco:`dataclass` decorator will raise a :exc:" +"`ValueError` if it detects an unhashable default parameter. The assumption " +"is that if a value is unhashable, it is mutable. This is a partial " +"solution, but it does protect against many common errors." msgstr "" -#: ../../library/dataclasses.rst:759 +#: ../../library/dataclasses.rst:789 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:792 +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:798 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:805 msgid "Descriptor-typed fields" msgstr "" -#: ../../library/dataclasses.rst:777 +#: ../../library/dataclasses.rst:807 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:810 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:814 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 -msgid "" -"To determine whether a field contains a default value, :func:`@dataclass " -"` will call the descriptor's :meth:`!__get__` method using its " -"class access form: ``descriptor.__get__(obj=None, type=cls)``. If the " -"descriptor returns a value in this case, it will be used as the field's " -"default. On the other hand, if the descriptor raises :exc:`AttributeError` " -"in this situation, no default value will be provided for the field." -msgstr "" - -#: ../../library/dataclasses.rst:823 +#: ../../library/dataclasses.rst:818 +msgid "" +"To determine whether a field contains a default value, :deco:`dataclass` " +"will call the descriptor's :meth:`!__get__` method using its class access " +"form: ``descriptor.__get__(obj=None, type=cls)``. If the descriptor returns " +"a value in this case, it will be used as the field's default. On the other " +"hand, if the descriptor raises :exc:`AttributeError` in this situation, no " +"default value will be provided for the field." +msgstr "" + +#: ../../library/dataclasses.rst:828 +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:853 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 " diff --git a/library/datatypes.po b/library/datatypes.po index 20c88e334..328754095 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..fa2be8511 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..786afae66 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 +# python-doc bot, 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-09-23 14:56+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,246 +54,377 @@ 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:270 ../../library/dbm.rst:471 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:242 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:182 ../../library/dbm.rst:374 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:184 ../../library/dbm.rst:247 +#: ../../library/dbm.rst:375 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:185 ../../library/dbm.rst:248 +#: ../../library/dbm.rst:376 ../../library/dbm.rst:452 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:186 ../../library/dbm.rst:249 +#: ../../library/dbm.rst:377 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:187 ../../library/dbm.rst:250 +#: ../../library/dbm.rst:378 ../../library/dbm.rst:454 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:264 ../../library/dbm.rst:380 +#: ../../library/dbm.rst:456 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 " -"stored, retrieved, and deleted, and the :keyword:`in` operator and the :meth:" -"`!keys` method are available, as well as :meth:`!get` and :meth:`!" -"setdefault` methods." +"The object returned by :func:`~dbm.open` supports the basic functionality of " +"mutable :term:`mappings `; keys and their corresponding values can " +"be stored, retrieved, and deleted, and iteration, the :keyword:`in` operator " +"and methods :meth:`!keys`, :meth:`!get`, :meth:`!setdefault` and :meth:`!" +"clear` are available. The :meth:`!keys` method returns a list instead of a " +"view object. The :meth:`!setdefault` method requires two arguments." msgstr "" -#: ../../library/dbm.rst:94 +#: ../../library/dbm.rst:95 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:99 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:102 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:106 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:110 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:114 +msgid ":meth:`!clear` methods are now available for all :mod:`dbm` backends." +msgstr "" + +#: ../../library/dbm.rst:118 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:121 +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:148 msgid "Module :mod:`shelve`" msgstr "Módulo :mod:`shelve`" -#: ../../library/dbm.rst:144 +#: ../../library/dbm.rst:149 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:152 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:155 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:163 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:167 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" -#: ../../library/dbm.rst:169 +#: ../../includes/wasm-notavail.rst:5 msgid "" -"Open an SQLite database. The returned object behaves like a :term:`mapping`, " -"implements a :meth:`!close` method, and supports a \"closing\" context " -"manager via the :keyword:`with` keyword." +"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:174 -msgid "The path to the database to be opened." +#: ../../library/dbm.rst:176 +msgid "Open an SQLite database." msgstr "" -#: ../../library/dbm.rst:185 +#: ../../library/dbm.rst:178 +msgid "The path to the database to be opened." +msgstr "O caminho para o banco de dados a ser aberta." + +#: ../../library/dbm.rst:189 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" +#: ../../library/dbm.rst:193 +msgid "" +"The returned database object behaves similar to a mutable :term:`mapping`, " +"but the :meth:`!keys` method returns a list, and the :meth:`!setdefault` " +"method requires two arguments. It also supports a \"closing\" context " +"manager via the :keyword:`with` keyword." msgstr "" -#: ../../library/dbm.rst:197 -msgid "**Source code:** :source:`Lib/dbm/gnu.py`" +#: ../../library/dbm.rst:198 ../../library/dbm.rst:399 +msgid "The following method is also provided:" +msgstr "O seguinte método também é fornecido:" + +#: ../../library/dbm.rst:202 +msgid "Close the SQLite database." msgstr "" -#: ../../library/dbm.rst:201 +#: ../../library/dbm.rst:206 +msgid ":mod:`dbm.gnu` --- GNU database manager" +msgstr ":mod:`dbm.gnu` --- Gerenciador de banco de dados do GNU" + +#: ../../library/dbm.rst:212 +msgid "**Source code:** :source:`Lib/dbm/gnu.py`" +msgstr "**Código-fonte:** :source:`Lib/dbm/gnu.py`" + +#: ../../library/dbm.rst:216 msgid "" "The :mod:`dbm.gnu` module provides an interface to the :abbr:`GDBM (GNU " "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:222 ../../library/dbm.rst:342 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." -#: ../../library/dbm.rst:212 +#: ../../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:229 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 -msgid "Open a GDBM database and return a :class:`!gdbm` object." +#: ../../library/dbm.rst:235 +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:240 +msgid "Open a GDBM database and return a :class:`!gdbm` object." +msgstr "Abre um banco de dados GDBM e retorna um objeto :class:`!gdbm`." -#: ../../library/dbm.rst:224 +#: ../../library/dbm.rst:246 msgid "" "* ``'r'`` (default): |flag_r| * ``'w'``: |flag_w| * ``'c'``: |flag_c| * " "``'n'``: |flag_n| The following additional characters may be appended to " @@ -304,72 +435,121 @@ 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:252 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:255 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:257 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:259 msgid "``'u'``: Do not lock database." -msgstr "" +msgstr "``'u'``: Não trava o banco de dados." -#: ../../library/dbm.rst:239 +#: ../../library/dbm.rst:261 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:267 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:273 msgid "" -"A string of characters the *flag* parameter of :meth:`~dbm.gnu.open` " -"supports." +":class:`!gdbm` objects behave similar to mutable :term:`mappings `, " +"but methods :meth:`!items`, :meth:`!values`, :meth:`!pop`, :meth:`!popitem`, " +"and :meth:`!update` are not supported, the :meth:`!keys` method returns a " +"list, and the :meth:`!setdefault` method requires two arguments. It also " +"supports a \"closing\" context manager via the :keyword:`with` keyword." msgstr "" -#: ../../library/dbm.rst:255 -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:" +#: ../../library/dbm.rst:280 ../../library/dbm.rst:393 +msgid "Added the :meth:`!get` and :meth:`!setdefault` methods." msgstr "" -#: ../../library/dbm.rst:261 +#: ../../library/dbm.rst:283 ../../library/dbm.rst:396 +msgid "Added the :meth:`!clear` method." +msgstr "" + +#: ../../library/dbm.rst:286 ../../library/dbm.rst:479 +msgid "The following methods are also provided:" +msgstr "" + +#: ../../library/dbm.rst:290 +msgid "Close the GDBM database." +msgstr "Fecha o banco de dados GDBM." + +#: ../../library/dbm.rst:294 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:301 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:305 +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:312 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 +557,230 @@ 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:320 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 -msgid "Close the GDBM database." -msgstr "" - -#: ../../library/dbm.rst:296 -msgid "Remove all items from the GDBM database." -msgstr "" - -#: ../../library/dbm.rst:302 +#: ../../library/dbm.rst:325 msgid ":mod:`dbm.ndbm` --- New Database Manager" -msgstr "" +msgstr ":mod:`dbm.ndbm` --- New Database Manager" -#: ../../library/dbm.rst:308 +#: ../../library/dbm.rst:331 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:335 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:347 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:356 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:362 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:367 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:369 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 -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 "" - -#: ../../library/dbm.rst:362 +#: ../../library/dbm.rst:383 msgid "Accepts :term:`path-like object` for filename." msgstr "Aceita um :term:`objeto caminho ou similar` como nome de arquivo." -#: ../../library/dbm.rst:367 -msgid "Close the NDBM database." +#: ../../library/dbm.rst:386 +msgid "" +":class:`!ndbm` objects behave similar to mutable :term:`mappings `, " +"but methods :meth:`!items`, :meth:`!values`, :meth:`!pop`, :meth:`!popitem`, " +"and :meth:`!update` are not supported, the :meth:`!keys` method returns a " +"list, and the :meth:`!setdefault` method requires two arguments. It also " +"supports a \"closing\" context manager via the :keyword:`with` keyword." msgstr "" -#: ../../library/dbm.rst:371 -msgid "Remove all items from the NDBM database." -msgstr "" +#: ../../library/dbm.rst:403 +msgid "Close the NDBM database." +msgstr "Fecha o banco de dados NDBM." -#: ../../library/dbm.rst:377 +#: ../../library/dbm.rst:407 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:412 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:418 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:425 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:430 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:434 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 -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." +#: ../../library/dbm.rst:440 +msgid "Open a :mod:`!dbm.dumb` database." msgstr "" -#: ../../library/dbm.rst:415 +#: ../../library/dbm.rst:442 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:443 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:446 msgid ":file:`{filename}.dat`" -msgstr "" +msgstr ":file:`{filename}.dat`" -#: ../../library/dbm.rst:420 +#: ../../library/dbm.rst:447 msgid ":file:`{filename}.dir`" -msgstr "" +msgstr ":file:`{filename}.dir`" -#: ../../library/dbm.rst:423 +#: ../../library/dbm.rst:450 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:451 msgid "``'r'``: |flag_r|" -msgstr "" +msgstr "``'r'``: |flag_r|" -#: ../../library/dbm.rst:426 +#: ../../library/dbm.rst:453 msgid "``'c'`` (default): |flag_c|" -msgstr "" +msgstr "``'c'`` (padrão): |flag_c|" -#: ../../library/dbm.rst:433 +#: ../../library/dbm.rst:460 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:464 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:467 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:474 msgid "" -"In addition to the methods provided by the :class:`collections.abc." -"MutableMapping` class, the following methods are provided:" +"The returned database object behaves similar to a mutable :term:`mapping`, " +"but the :meth:`!keys` and :meth:`!items` methods return lists, and the :meth:" +"`!setdefault` method requires two arguments. It also supports a \"closing\" " +"context manager via the :keyword:`with` keyword." msgstr "" -#: ../../library/dbm.rst:453 +#: ../../library/dbm.rst:483 +msgid "Close the database." +msgstr "Fecha o banco de dados." + +#: ../../library/dbm.rst:487 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 -msgid "Close the database." -msgstr "" - -#: ../../library/dbm.rst:384 +#: ../../library/dbm.rst:414 msgid "databases" -msgstr "" +msgstr "bancos de dados" diff --git a/library/debug.po b/library/debug.po index fb948bd30..408b2ac04 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..ad24f1b33 100644 --- a/library/decimal.po +++ b/library/decimal.po @@ -1,29 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,7 +217,7 @@ msgstr "" "Arithmetic Specification `_." #: ../../library/decimal.rst:125 -msgid "Quick-start Tutorial" +msgid "Quick-start tutorial" msgstr "Tutorial de início rápido" #: ../../library/decimal.rst:127 @@ -233,6 +230,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 +263,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 +311,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 +349,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 +381,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 +401,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 +501,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 +558,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 +594,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 +653,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 +707,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 +721,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 +733,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 +745,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 +764,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 +772,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 +789,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 +801,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 +824,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 +844,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 +862,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 +870,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 +878,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 +890,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 +900,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 +923,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 +933,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 +942,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 +964,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 +978,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 +994,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 +1006,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 +1018,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 +1026,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 +1035,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 +1044,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 +1052,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 +1062,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 +1070,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 +1084,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 +1092,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 +1120,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 +1130,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 +1138,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 +1146,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 +1154,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 +1162,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 +1170,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 +1178,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 +1186,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 +1194,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 +1202,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 +1210,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 +1218,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 +1231,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 +1241,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 +1249,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 +1259,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 +1269,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 +1279,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 +1287,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 +1297,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 +1305,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 +1315,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 +1325,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 +1337,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 +1345,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 +1362,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 +1370,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 +1384,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 +1392,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 +1445,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 +1458,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 +1466,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 +1480,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 +1488,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 +1496,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 +1511,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 +1536,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 +1553,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 +1572,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 +1593,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 +1607,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 +1620,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 +1630,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 +1648,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 +1669,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 +1677,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 +1691,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 +1741,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 +1755,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 +1763,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 +1779,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 +1793,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 +1802,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 +1846,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 +1854,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 +1863,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 +1877,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 +1897,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 +1909,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 +1921,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 +1934,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 +1942,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 +1952,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 +1960,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 +1971,86 @@ 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." +"Um inteiro no intervalo [``1``, :const:`MAX_PREC`] que define a precisão " +"para 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 "Uma das constantes listadas na seção `Modos de arredondamento`_." + +#: ../../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`_." +"Listas de todos os sinais a serem configurados. Geralmente, novos contextos " +"devem apenas definir armadilhas e deixar os sinalizadores limpos." -#: ../../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." +"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: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 "" +"Assume ``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úsculo é " +"usado: ``Decimal('6.02e+23')``." #: ../../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 "" +"Assume ``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::" + +#: ../../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 +2072,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 +2099,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 +2113,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 +2137,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 +2149,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 +2179,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 +2198,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 +2392,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 +2412,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 +2420,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 +2430,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 +2438,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 +2469,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 +2489,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 +2497,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 +2541,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 +2593,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 +2635,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 +2648,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 +2661,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 +2673,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 +2687,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 +2706,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 +2720,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 +2732,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 +2772,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 +2789,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 +2802,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 +2814,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 +2839,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 +2849,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" +#: ../../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 "Observações sobre ponto flutuante" -#: ../../library/decimal.rst:1749 +#: ../../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 +2899,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 +2913,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 +2955,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 +2997,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 +3011,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 +3022,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 +3041,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 +3051,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 +3082,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 +3094,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 +3108,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 +3124,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 +3132,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 +3142,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 +3157,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 +3198,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 moeda.\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" +" \"\"\"Calcula Pi com a precisão atual.\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 +3513,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 +3527,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 +3537,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 +3545,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 +3557,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 +3565,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 +3577,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 +3585,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 +3604,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 +3638,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 +3650,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 +3660,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 +3675,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 +3692,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 +3705,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 +3715,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 +3729,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 +3751,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 +3769,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 +3807,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 +3815,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 +3859,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 +3914,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..80e71b289 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..8c16f952e 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c7acc9aec 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0a631af6f 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 +# python-doc bot, 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-10-07 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -322,7 +316,7 @@ msgid "" "*linejunk*: A function that accepts a single string argument, and returns " "true if the string is junk, or false if not. The default is ``None``. There " "is also a module-level function :func:`IS_LINE_JUNK`, which filters out " -"lines without visible characters, except for at most one pound character " +"lines without visible characters, except for at most one hash character " "(``'#'``) -- however the underlying :class:`SequenceMatcher` class does a " "dynamic analysis of which lines are so frequent as to constitute noise, and " "this usually works better than using this function." @@ -416,15 +410,14 @@ msgstr "" #: ../../library/difflib.rst:354 msgid "" -"`Pattern Matching: The Gestalt Approach `_" +"`Pattern Matching: The Gestalt Approach `_" msgstr "" #: ../../library/difflib.rst:355 msgid "" "Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. " -"This was published in `Dr. Dobb's Journal `_ in " -"July, 1988." +"This was published in Dr. Dobb's Journal in July, 1988." msgstr "" #: ../../library/difflib.rst:362 @@ -444,6 +437,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 +563,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 +624,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 +679,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 +861,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 +935,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..13a922968 100644 --- a/library/dis.po +++ b/library/dis.po @@ -1,30 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-21 15:05+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +122,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 +138,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 +169,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 +185,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 +199,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 +213,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 +223,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 +234,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 +246,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 +256,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 +264,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 +272,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 +280,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 +289,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 +307,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 +315,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 +369,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 +379,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 +389,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 +399,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 +407,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 +441,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 +450,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 +458,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 +466,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 +474,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 +489,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 +501,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 +538,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 +546,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 +554,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 +570,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 +582,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 +597,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 +612,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 +629,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 +645,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 +657,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 +669,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 +681,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 +689,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 +710,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 +723,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 +753,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 +761,27 @@ 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 "" +"Informações sobre as entradas de cache desta instrução, como tripletos do " +"formato ``(nome, tamanho, dados)``, onde ``nome`` e ``tamanho`` descrevem o " +"formato do cache e dados são o conteúdo do cache. ``cache_info`` é ``None`` " +"se a instrução não tiver caches." + +#: ../../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 +791,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 +817,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 +825,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 "STACK.pop()" + +#: ../../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 +841,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 +854,23 @@ 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 "" +"assert i > 0\n" +"STACK.append(STACK[-i])" + +#: ../../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 " @@ -802,11 +878,11 @@ msgid "" "viewed with ``show_caches=True``." msgstr "" "Ao invés de ser uma instrução de fato, este opcode é usado para demarcar " -"espaço extra para o interpretador armazernar dados úteis diretamente no " +"espaço extra para o interpretador armazenar dados úteis diretamente no " "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 +892,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 +902,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 +914,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 +946,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 +964,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 +974,93 @@ 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 "" +"rhs = STACK.pop()\n" +"lhs = STACK.pop()\n" +"STACK.append(lhs op rhs)" + +#: ../../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 "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"value = STACK.pop()\n" +"container[key] = value" + +#: ../../library/dis.rst:696 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"del container[key]" +msgstr "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"del container[key]" + +#: ../../library/dis.rst:704 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[start:end])" +msgstr "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[start:end])" + +#: ../../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 "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"values = STACK.pop()\n" +"container[start:end] = value" + +#: ../../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 +1072,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 +1107,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 +1119,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 +1139,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 +1147,53 @@ 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 "" +"item = STACK.pop()\n" +"set.add(STACK[-i], item)" + +#: ../../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 "" +"item = STACK.pop()\n" +"list.append(STACK[-i], item)" + +#: ../../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 "" +"value = STACK.pop()\n" +"key = STACK.pop()\n" +"dict.__setitem__(STACK[-i], key, value)" + +#: ../../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 +1201,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 +1213,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 +1237,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 +1245,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 +1257,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." @@ -1101,9 +1272,9 @@ msgid "" msgstr "" "Re-levanta a exceção que se encontra no topo da pilha. Se o oparg não for " "zero, remove um valor adicional do topo da pilha, o qual é atribuído ao :" -"attr:`~frame.f_lasti`` do quadro atual." +"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 +1284,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 +1294,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 +1302,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 " @@ -1142,9 +1313,9 @@ msgstr "" "nela o subgrupo que falhou a correspondência (``None`` caso a " "correspondência tenha sido total), seguido pelo subgrupo que correspondeu. " "Quando não há correspondência nenhuma, remove um item (o tipo da " -"correspondêcia) e põe ``None`` no seu lugar." +"correspondência) 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 +1327,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 +1335,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 +1343,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 +1351,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 +1365,15 @@ 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 "" +"Executa ``STACK.append(len(STACK[-1]))``. Usado em instruções :keyword:" +"`match` onde a comparação com a estrutura do padrão é necessária." -#: ../../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 +1385,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 +1399,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 +1410,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 +1418,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 +1438,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 +1447,15 @@ 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 "" +"assert(len(STACK[-1]) == count)\n" +"STACK.extend(STACK.pop()[:-count-1:-1])" + +#: ../../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 +1467,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 +1488,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 +1497,17 @@ 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 "" +"obj = STACK.pop()\n" +"value = STACK.pop()\n" +"obj.name = value" + +#: ../../library/dis.rst:1052 msgid "" "where *namei* is the index of name in :attr:`~codeobject.co_names` of the :" "ref:`code object `." @@ -1322,7 +1515,15 @@ 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 "" +"obj = STACK.pop()\n" +"del obj.name" + +#: ../../library/dis.rst:1062 msgid "" "where *namei* is the index of name into :attr:`~codeobject.co_names` of the :" "ref:`code object `." @@ -1330,21 +1531,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 +1553,17 @@ 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 "" +"Envia uma referência ao dicionário local para a pilha. Isso é usado para " +"preparar dicionários de espaço de nomes para :opcode:" +"`LOAD_FROM_DICT_OR_DEREF` e :opcode:`LOAD_FROM_DICT_OR_GLOBALS`." -#: ../../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 " @@ -1367,70 +1571,104 @@ msgid "" "variables in :ref:`annotation scopes ` within class " "bodies." msgstr "" +"Extrai um mapeamento da pilha e procura o valor de ``co_names[namei]``. Se o " +"nome não for encontrado, procura-o nas variáveis globais e, em seguida, nas " +"variáveis embutidas, semelhante a :opcode:`LOAD_GLOBAL`. Isso é usado para " +"carregar variáveis globais em :ref:`escopos de anotação ` " +"dentro dos corpos de classe." -#: ../../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 +1680,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 +1758,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 +1821,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 +2036,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 +2070,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 +2125,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 +2191,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 +2474,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..af8af26be 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0bf22bcc8 --- /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: +# python-doc bot, 2025 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.13\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" +"Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" +"teams/5390/pt_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..6d681f9b1 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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, " @@ -169,36 +359,24 @@ msgstr "" #: ../../library/doctest.rst:171 msgid "" "You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, " -"or prohibit it by passing ``verbose=False``. In either of those cases, " -"``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not " +"or prohibit it by passing ``verbose=False``. In either of those cases, :" +"data:`sys.argv` is not examined by :func:`testmod` (so passing ``-v`` or not " "has no effect)." msgstr "" "Você pode forçar o modo verboso passando ``verbose=True`` para :func:" "`testmod`, ou proibi-lo passando ``verbose=False``. Em qualquer um desses " -"casos, ``sys.argv`` não é examinado por :func:`testmod` (então passar ``-v`` " -"ou não não tem efeito)." +"casos, :data:`sys.argv` não é examinado por :func:`testmod` (então passar ``-" +"v`` ou não não tem efeito)." #: ../../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::" +"There is also a command line shortcut for running :func:`testmod`, see " +"section :ref:`doctest-cli`." 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:" +"Há também um atalho de linha de comando para executar :func:`testmod`, veja " +"a seção :ref:`doctest-cli`." -#: ../../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." -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 +384,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 +396,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 +417,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,19 +459,37 @@ 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 " "cause(s) of the failure(s) are printed to stdout, using the same format as :" -"func:`testmod`." +"func:`!testmod`." msgstr "" "Assim como :func:`testmod`, :func:`testfile` não vai exibir nada a menos que " "um exemplo falhe. Se um exemplo falhar, então o(s) exemplo(s) com falha e " "a(s) causa(s) da(s) falha(s) são impressos em stdout, usando o mesmo formato " -"que :func:`testmod`." +"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 +501,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 +510,15 @@ 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`." +"Há também um atalho de linha de comando para executar :func:`testfile`, veja " +"a seção :ref:`doctest-cli`." -#: ../../library/doctest.rst:256 +#: ../../library/doctest.rst:243 msgid "" "For more information on :func:`testfile`, see section :ref:`doctest-basic-" "api`." @@ -299,11 +526,71 @@ 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 "Uso na linha de comando" + +#: ../../library/doctest.rst:251 +msgid "" +"The :mod:`doctest` module can be invoked as a script from the command line:" +msgstr "" +"O módulo :mod:`doctest` pode ser invocado como um script na linha de comando:" + +#: ../../library/doctest.rst:253 +msgid "python -m doctest [-v] [-o OPTION] [-f] file [file ...]" +msgstr "python -m doctest [-v] [-o OPÇÃO] [-f] arquivo [arquivo ...]" + +#: ../../library/doctest.rst:261 +msgid "" +"Detailed report of all examples tried is printed to standard output, along " +"with assorted summaries at the end::" +msgstr "" +"Relatório detalhado de todos os exemplos testados é impresso na saída " +"padrão, junto com diversos resumos no final." + +#: ../../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 "" +"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: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 "" +"Se o nome do arquivo não termina com :file:`.py`, :mod:`!doctest` infere que " +"ele deve ser executado com :func:`testfile`::" + +#: ../../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 "" +"Os sinalizadores de opção controlam vários aspectos do comportamento do " +"doctest, consulte a seção :ref:`doctest-options`." + +#: ../../library/doctest.rst:284 +msgid "This is shorthand for ``-o FAIL_FAST``." +msgstr "Este é um atalho para ``-o FAIL_FAST``." + +#: ../../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 +607,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 +619,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:317 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 +641,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:326 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:328 +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:340 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 +682,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:346 msgid "" "Any classes found are recursively searched similarly, to test docstrings in " "their contained methods and nested classes." @@ -382,11 +691,23 @@ msgstr "" "semelhante, para testar docstrings em seus métodos contidos e classes " "aninhadas." -#: ../../library/doctest.rst:316 +#: ../../library/doctest.rst:351 +msgid "" +"``doctest`` can only automatically discover classes and functions that are " +"defined at the module level or inside other classes." +msgstr "" + +#: ../../library/doctest.rst:354 +msgid "" +"Since nested classes and functions only exist when an outer function is " +"called, they cannot be discovered. Define them outside to make them visible." +msgstr "" + +#: ../../library/doctest.rst:360 msgid "How are Docstring Examples Recognized?" msgstr "Como os exemplos de docstrings são reconhecidos?" -#: ../../library/doctest.rst:318 +#: ../../library/doctest.rst:362 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 +717,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:367 +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:387 msgid "" "Any expected output must immediately follow the final ``'>>> '`` or ``'... " "'`` line containing the code, and the expected output (if any) extends to " @@ -406,11 +761,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:391 msgid "The fine print:" msgstr "A saída formatada:" -#: ../../library/doctest.rst:349 +#: ../../library/doctest.rst:393 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 +777,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:398 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 +804,7 @@ msgstr "" "para lidar com guias escrevendo uma classe :class:`DocTestParser` " "personalizada." -#: ../../library/doctest.rst:366 +#: ../../library/doctest.rst:410 msgid "" "Output to stdout is captured, but not output to stderr (exception tracebacks " "are captured via a different means)." @@ -457,7 +812,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:413 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 +823,21 @@ msgstr "" "deverá usar uma docstring bruta, que preservará suas barras invertidas " "exatamente como você as digita::" -#: ../../library/doctest.rst:379 +#: ../../library/doctest.rst:417 +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:423 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 +849,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:427 +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:433 msgid "The starting column doesn't matter::" msgstr "A coluna inicial não importa::" -#: ../../library/doctest.rst:396 +#: ../../library/doctest.rst:435 +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:440 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 +888,11 @@ msgstr "" "esperada quantos apareceram na linha inicial ``'>>> '`` que iniciou o " "exemplo." -#: ../../library/doctest.rst:403 +#: ../../library/doctest.rst:447 msgid "What's the Execution Context?" msgstr "Qual é o contexto de execução?" -#: ../../library/doctest.rst:405 +#: ../../library/doctest.rst:449 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 +911,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:457 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 +919,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:464 msgid "What About Exceptions?" msgstr "E quanto às exceções?" -#: ../../library/doctest.rst:422 +#: ../../library/doctest.rst:466 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 +937,54 @@ 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:472 msgid "Simple example::" msgstr "Exemplo simples::" -#: ../../library/doctest.rst:435 +#: ../../library/doctest.rst:474 +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:479 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:482 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 "" +"A saída esperada para uma exceção deve começar com um cabeçalho do " +"traceback, que pode ser qualquer uma das duas linhas a seguir, indentadas da " +"mesma forma que a primeira linha do exemplo::" -#: ../../library/doctest.rst:445 +#: ../../library/doctest.rst:486 +msgid "" +"Traceback (most recent call last):\n" +"Traceback (innermost last):" +msgstr "" + +#: ../../library/doctest.rst:489 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:493 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 +992,40 @@ msgid "" "multi-line detail::" msgstr "" -#: ../../library/doctest.rst:461 +#: ../../library/doctest.rst:498 +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:505 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:508 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:511 +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:518 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 +1034,11 @@ msgid "" "transcript of a Monty Python skit." msgstr "" -#: ../../library/doctest.rst:480 +#: ../../library/doctest.rst:524 msgid "Some details you should read once, but won't need to remember:" msgstr "" -#: ../../library/doctest.rst:482 +#: ../../library/doctest.rst:526 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 +1048,7 @@ msgid "" "create real problems." msgstr "" -#: ../../library/doctest.rst:489 +#: ../../library/doctest.rst:533 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,29 +1057,38 @@ msgid "" "course this does the right thing for genuine tracebacks." msgstr "" -#: ../../library/doctest.rst:495 +#: ../../library/doctest.rst:539 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:543 msgid "" "The interactive shell omits the traceback header line for some :exc:" "`SyntaxError`\\ s. But doctest uses the traceback header line to " "distinguish exceptions from non-exceptions. So in the rare case where you " -"need to test a :exc:`SyntaxError` that omits the traceback header, you will " +"need to test a :exc:`!SyntaxError` that omits the traceback header, you will " "need to manually add the traceback header line to your test example." msgstr "" -#: ../../library/doctest.rst:507 +#: ../../library/doctest.rst:551 msgid "" "For some exceptions, Python displays the position of the error using ``^`` " "markers and tildes::" msgstr "" -#: ../../library/doctest.rst:516 +#: ../../library/doctest.rst:554 +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:560 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 +1096,20 @@ msgid "" "location::" msgstr "" -#: ../../library/doctest.rst:531 +#: ../../library/doctest.rst:564 +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:575 msgid "Option Flags" msgstr "Flags opcionais" -#: ../../library/doctest.rst:533 +#: ../../library/doctest.rst:577 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 +1119,13 @@ msgid "" "option." msgstr "" -#: ../../library/doctest.rst:539 -msgid "The ``-o`` command line option." -msgstr "" - -#: ../../library/doctest.rst:542 +#: ../../library/doctest.rst:583 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:589 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 +1137,7 @@ msgid "" "not for several years." msgstr "" -#: ../../library/doctest.rst:560 +#: ../../library/doctest.rst:601 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 +1146,7 @@ msgid "" "`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed." msgstr "" -#: ../../library/doctest.rst:569 +#: ../../library/doctest.rst:610 msgid "" "When specified, all sequences of whitespace (blanks and newlines) are " "treated as equal. Any sequence of whitespace within the expected output " @@ -704,7 +1156,7 @@ msgid "" "across multiple lines in your source." msgstr "" -#: ../../library/doctest.rst:580 +#: ../../library/doctest.rst:621 msgid "" "When specified, an ellipsis marker (``...``) in the expected output can " "match any substring in the actual output. This includes substrings that " @@ -713,14 +1165,14 @@ msgid "" "matched too much!\" surprises that ``.*`` is prone to in regular expressions." msgstr "" -#: ../../library/doctest.rst:589 +#: ../../library/doctest.rst:630 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:634 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 +1182,35 @@ msgid "" "these variations will work with the flag specified:" msgstr "" -#: ../../library/doctest.rst:615 +#: ../../library/doctest.rst:642 +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:656 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:660 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:667 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 +1219,32 @@ msgid "" "might depend on resources which would be unavailable to the test driver." msgstr "" -#: ../../library/doctest.rst:632 +#: ../../library/doctest.rst:673 msgid "" "The SKIP flag can also be used for temporarily \"commenting out\" examples." msgstr "" -#: ../../library/doctest.rst:637 +#: ../../library/doctest.rst:678 msgid "A bitmask or'ing together all the comparison flags above." msgstr "" -#: ../../library/doctest.rst:639 +#: ../../library/doctest.rst:680 msgid "The second group of options controls how test failures are reported:" msgstr "" -#: ../../library/doctest.rst:644 +#: ../../library/doctest.rst:685 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:691 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:697 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 +1254,7 @@ msgid "" "mismatching column positions." msgstr "" -#: ../../library/doctest.rst:665 +#: ../../library/doctest.rst:706 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 +1265,7 @@ msgid "" "of failures reported; only the output is suppressed." msgstr "" -#: ../../library/doctest.rst:676 +#: ../../library/doctest.rst:717 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 +1273,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:725 msgid "A bitmask or'ing together all the reporting flags above." msgstr "" -#: ../../library/doctest.rst:692 +#: ../../library/doctest.rst:728 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:734 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 +1292,46 @@ msgid "" "be called using the following idiom::" msgstr "" -#: ../../library/doctest.rst:714 +#: ../../library/doctest.rst:740 +msgid "MY_FLAG = register_optionflag('MY_FLAG')" +msgstr "" + +#: ../../library/doctest.rst:750 msgid "Directives" msgstr "" -#: ../../library/doctest.rst:716 +#: ../../library/doctest.rst:752 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:763 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:767 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:770 msgid "For example, this test passes:" msgstr "Por exemplo, este teste é aprovado:" -#: ../../library/doctest.rst:743 +#: ../../library/doctest.rst:772 +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:779 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 +1339,52 @@ msgid "" "a directive to do so:" msgstr "" -#: ../../library/doctest.rst:754 +#: ../../library/doctest.rst:784 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:790 msgid "" "Multiple directives can be used on a single physical line, separated by " "commas:" msgstr "" -#: ../../library/doctest.rst:763 +#: ../../library/doctest.rst:793 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:799 msgid "" "If multiple directive comments are used for a single example, then they are " "combined:" msgstr "" -#: ../../library/doctest.rst:773 +#: ../../library/doctest.rst:802 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"... # doctest: +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + +#: ../../library/doctest.rst:809 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:813 +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:820 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 +1394,11 @@ msgid "" "be useful." msgstr "" -#: ../../library/doctest.rst:794 +#: ../../library/doctest.rst:830 msgid "Warnings" msgstr "Avisos" -#: ../../library/doctest.rst:796 +#: ../../library/doctest.rst:832 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 +1408,101 @@ msgid "" "test like ::" msgstr "" -#: ../../library/doctest.rst:805 +#: ../../library/doctest.rst:838 +msgid "" +">>> foo()\n" +"{\"spam\", \"eggs\"}" +msgstr "" + +#: ../../library/doctest.rst:841 msgid "is vulnerable! One workaround is to do ::" msgstr "" -#: ../../library/doctest.rst:810 +#: ../../library/doctest.rst:843 +msgid "" +">>> foo() == {\"spam\", \"eggs\"}\n" +"True" +msgstr "" + +#: ../../library/doctest.rst:846 msgid "instead. Another is to do ::" msgstr "" -#: ../../library/doctest.rst:816 +#: ../../library/doctest.rst:848 +msgid "" +">>> d = sorted(foo())\n" +">>> d\n" +"['eggs', 'spam']" +msgstr "" + +#: ../../library/doctest.rst:852 msgid "There are others, but you get the idea." msgstr "" -#: ../../library/doctest.rst:818 +#: ../../library/doctest.rst:854 msgid "Another bad idea is to print things that embed an object address, like" msgstr "" -#: ../../library/doctest.rst:828 +#: ../../library/doctest.rst:856 +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:864 msgid "" "The :const:`ELLIPSIS` directive gives a nice approach for the last example:" msgstr "" -#: ../../library/doctest.rst:836 +#: ../../library/doctest.rst:866 +msgid "" +">>> C() # doctest: +ELLIPSIS\n" +"" +msgstr "" + +#: ../../library/doctest.rst:872 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. ::" +"platforms, because Python defers to the platform C library for some floating-" +"point calculations, and C libraries vary widely in quality here. ::" +msgstr "" + +#: ../../library/doctest.rst:876 +msgid "" +">>> 1000**0.1 # risky\n" +"1.9952623149688797\n" +">>> round(1000**0.1, 9) # safer\n" +"1.995262315\n" +">>> print(f'{1000**0.1:.4f}') # much safer\n" +"1.9953" msgstr "" -#: ../../library/doctest.rst:847 +#: ../../library/doctest.rst:883 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:886 +msgid "" +">>> 3./4 # utterly safe\n" +"0.75" +msgstr "" + +#: ../../library/doctest.rst:889 msgid "" "Simple fractions are also easier for people to understand, and that makes " "for better documentation." msgstr "" -#: ../../library/doctest.rst:860 +#: ../../library/doctest.rst:896 msgid "Basic API" msgstr "" -#: ../../library/doctest.rst:862 +#: ../../library/doctest.rst:898 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 +1510,25 @@ msgid "" "simple-testmod` and :ref:`doctest-simple-testfile`." msgstr "" -#: ../../library/doctest.rst:870 +#: ../../library/doctest.rst:906 msgid "" "All arguments except *filename* are optional, and should be specified in " "keyword form." msgstr "" -#: ../../library/doctest.rst:873 +#: ../../library/doctest.rst:909 msgid "" "Test examples in the file named *filename*. Return ``(failure_count, " "test_count)``." msgstr "" -#: ../../library/doctest.rst:876 +#: ../../library/doctest.rst:912 msgid "" "Optional argument *module_relative* specifies how the filename should be " "interpreted:" msgstr "" -#: ../../library/doctest.rst:879 +#: ../../library/doctest.rst:915 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 +1538,20 @@ msgid "" "absolute path (i.e., it may not begin with ``/``)." msgstr "" -#: ../../library/doctest.rst:886 +#: ../../library/doctest.rst:922 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:926 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:929 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 +1560,7 @@ msgid "" "is an error to specify *package* if *module_relative* is ``False``." msgstr "" -#: ../../library/doctest.rst:899 +#: ../../library/doctest.rst:935 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 +1568,7 @@ msgid "" "``None``, a new empty dict is used." msgstr "" -#: ../../library/doctest.rst:904 +#: ../../library/doctest.rst:940 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 +1581,27 @@ msgid "" "tested." msgstr "" -#: ../../library/doctest.rst:913 +#: ../../library/doctest.rst:949 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``." +"v'`` is in :data:`sys.argv`." msgstr "" -#: ../../library/doctest.rst:917 +#: ../../library/doctest.rst:953 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:957 msgid "" -"Optional argument *optionflags* (default value 0) takes the :ref:`bitwise OR " -"` of option flags. See section :ref:`doctest-options`." +"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:961 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 +1609,33 @@ msgid "" "continue running examples." msgstr "" -#: ../../library/doctest.rst:930 ../../library/doctest.rst:1072 +#: ../../library/doctest.rst:966 ../../library/doctest.rst:1109 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:970 ../../library/doctest.rst:1113 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:976 msgid "" "All arguments are optional, and all except for *m* should be specified in " "keyword form." msgstr "" -#: ../../library/doctest.rst:943 +#: ../../library/doctest.rst:979 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:983 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 +1643,22 @@ msgid "" "directly, as if they were docstrings." msgstr "" -#: ../../library/doctest.rst:952 +#: ../../library/doctest.rst:988 msgid "" "Only docstrings attached to objects belonging to module *m* are searched." msgstr "" -#: ../../library/doctest.rst:954 +#: ../../library/doctest.rst:990 msgid "Return ``(failure_count, test_count)``." msgstr "" -#: ../../library/doctest.rst:956 +#: ../../library/doctest.rst:992 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:995 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 +1669,39 @@ msgid "" "defaults to true." msgstr "" -#: ../../library/doctest.rst:967 +#: ../../library/doctest.rst:1003 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:1010 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:1013 msgid "" "A shallow copy of dictionary argument *globs* is used for the execution " "context." msgstr "" -#: ../../library/doctest.rst:979 +#: ../../library/doctest.rst:1015 msgid "" "Optional argument *name* is used in failure messages, and defaults to " "``\"NoName\"``." msgstr "" -#: ../../library/doctest.rst:982 +#: ../../library/doctest.rst:1018 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:1021 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 +1709,16 @@ msgid "" "found in *globs*." msgstr "" -#: ../../library/doctest.rst:989 +#: ../../library/doctest.rst:1025 msgid "" "Optional argument *optionflags* works as for function :func:`testfile` above." msgstr "" -#: ../../library/doctest.rst:995 +#: ../../library/doctest.rst:1031 msgid "Unittest API" msgstr "API do Unittest" -#: ../../library/doctest.rst:997 +#: ../../library/doctest.rst:1033 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,44 +1728,55 @@ msgid "" "your test module::" msgstr "" -#: ../../library/doctest.rst:1011 +#: ../../library/doctest.rst:1039 +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:1047 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:1053 msgid "" "Convert doctest tests from one or more text files to a :class:`unittest." "TestSuite`." msgstr "" -#: ../../library/doctest.rst:1020 +#: ../../library/doctest.rst:1056 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 " -"any file fails, then the synthesized unit test fails, and a :exc:" -"`failureException` exception is raised showing the name of the file " +"any file fails, then the synthesized unit test fails, and a :exc:`~unittest." +"TestCase.failureException` exception is raised showing the name of the file " "containing the test and a (sometimes approximate) line number. If all the " "examples in a file are skipped, then the synthesized unit test is also " "marked as skipped." msgstr "" -#: ../../library/doctest.rst:1027 +#: ../../library/doctest.rst:1063 msgid "Pass one or more paths (as strings) to text files to be examined." msgstr "" -#: ../../library/doctest.rst:1029 +#: ../../library/doctest.rst:1065 msgid "Options may be provided as keyword arguments:" msgstr "" -#: ../../library/doctest.rst:1031 +#: ../../library/doctest.rst:1067 msgid "" "Optional argument *module_relative* specifies how the filenames in *paths* " "should be interpreted:" msgstr "" -#: ../../library/doctest.rst:1034 +#: ../../library/doctest.rst:1070 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 +1787,14 @@ msgid "" "``)." msgstr "" -#: ../../library/doctest.rst:1042 +#: ../../library/doctest.rst:1078 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:1082 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,30 +1804,31 @@ msgid "" "``False``." msgstr "" -#: ../../library/doctest.rst:1053 +#: ../../library/doctest.rst:1089 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 " -"will be passed a :class:`DocTest` object. The setUp function can access the " -"test globals as the *globs* attribute of the test passed." +"will be passed a :class:`DocTest` object. The *setUp* function can access " +"the test globals as the :attr:`~DocTest.globs` attribute of the test passed." msgstr "" -#: ../../library/doctest.rst:1058 +#: ../../library/doctest.rst:1094 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* " -"function will be passed a :class:`DocTest` object. The setUp function can " -"access the test globals as the *globs* attribute of the test passed." +"function will be passed a :class:`DocTest` object. The *tearDown* function " +"can access the test globals as the :attr:`~DocTest.globs` attribute of the " +"test passed." msgstr "" -#: ../../library/doctest.rst:1063 ../../library/doctest.rst:1098 +#: ../../library/doctest.rst:1100 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:1104 msgid "" "Optional argument *optionflags* specifies the default doctest options for " "the tests, created by or-ing together individual option flags. See section :" @@ -1276,70 +1836,71 @@ msgid "" "for a better way to set reporting options." msgstr "" -#: ../../library/doctest.rst:1079 +#: ../../library/doctest.rst:1116 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:1122 msgid "Convert doctest tests for a module to a :class:`unittest.TestSuite`." msgstr "" -#: ../../library/doctest.rst:1087 +#: ../../library/doctest.rst:1124 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, " -"then the synthesized unit test fails, and a :exc:`failureException` " -"exception is raised showing the name of the file containing the test and a " -"(sometimes approximate) line number. If all the examples in a docstring are " -"skipped, then the synthesized unit test is also marked as skipped." +"framework and runs each doctest in the module. Each docstring is run as a " +"separate unit test. If any of the doctests fail, then the synthesized unit " +"test fails, and a :exc:`unittest.TestCase.failureException` exception is " +"raised showing the name of the file containing the test and a (sometimes " +"approximate) line number. If all the examples in a docstring are skipped, " +"then the" msgstr "" -#: ../../library/doctest.rst:1094 +#: ../../library/doctest.rst:1132 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:1136 +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 the module's :attr:`~module.__dict__`." +msgstr "" + +#: ../../library/doctest.rst:1140 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:1143 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:1146 msgid "" "Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as " -"for function :func:`DocFileSuite` above." +"for function :func:`DocFileSuite` above, but they are called for each " +"docstring." msgstr "" -#: ../../library/doctest.rst:1111 +#: ../../library/doctest.rst:1149 msgid "This function uses the same search technique as :func:`testmod`." msgstr "" -#: ../../library/doctest.rst:1113 +#: ../../library/doctest.rst:1151 msgid "" ":func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if " "*module* contains no docstrings instead of raising :exc:`ValueError`." msgstr "" -#: ../../library/doctest.rst:1119 -msgid "" -"When doctests which have been converted to unit tests by :func:" -"`DocFileSuite` or :func:`DocTestSuite` fail, this exception is raised " -"showing the name of the file containing the test and a (sometimes " -"approximate) line number." -msgstr "" - -#: ../../library/doctest.rst:1123 +#: ../../library/doctest.rst:1155 msgid "" "Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` " "out of :class:`!doctest.DocTestCase` instances, and :class:`!DocTestCase` is " @@ -1348,67 +1909,67 @@ msgid "" "questions about the exact details of :mod:`unittest` integration." msgstr "" -#: ../../library/doctest.rst:1129 +#: ../../library/doctest.rst:1161 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:1165 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 :" -"mod:`doctest` functions yourself, you can control the :mod:`doctest` options " -"in use directly, by passing option flags to :mod:`doctest` functions. " -"However, if you're writing a :mod:`unittest` framework, :mod:`unittest` " -"ultimately controls when and how tests get run. The framework author " -"typically wants to control :mod:`doctest` reporting options (perhaps, e.g., " -"specified by command line options), but there's no way to pass options " -"through :mod:`unittest` to :mod:`doctest` test runners." +"mod:`doctest` functions yourself, you can control the :mod:`!doctest` " +"options in use directly, by passing option flags to :mod:`!doctest` " +"functions. However, if you're writing a :mod:`unittest` framework, :mod:`!" +"unittest` ultimately controls when and how tests get run. The framework " +"author typically wants to control :mod:`!doctest` reporting options " +"(perhaps, e.g., specified by command line options), but there's no way to " +"pass options through :mod:`!unittest` to :mod:`!doctest` test runners." msgstr "" -#: ../../library/doctest.rst:1143 +#: ../../library/doctest.rst:1175 msgid "" -"For this reason, :mod:`doctest` also supports a notion of :mod:`doctest` " +"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:1181 msgid "Set the :mod:`doctest` reporting flags to use." msgstr "" -#: ../../library/doctest.rst:1151 +#: ../../library/doctest.rst:1183 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:1186 msgid "" "This is a module-global setting, and affects all future doctests run by " "module :mod:`unittest`: the :meth:`!runTest` method of :class:`!" "DocTestCase` looks at the option flags specified for the test case when the :" "class:`!DocTestCase` instance was constructed. If no reporting flags were " -"specified (which is the typical and expected case), :mod:`!doctest`'s :mod:" -"`unittest` reporting flags are :ref:`bitwise ORed ` into the option " +"specified (which is the typical and expected case), :mod:`!doctest`'s :mod:`!" +"unittest` reporting flags are :ref:`bitwise ORed ` into the option " "flags, and the option flags so augmented are passed to the :class:" "`DocTestRunner` instance created to run the doctest. If any reporting flags " "were specified when the :class:`!DocTestCase` instance was constructed, :mod:" -"`!doctest`'s :mod:`unittest` reporting flags are ignored." +"`!doctest`'s :mod:`!unittest` reporting flags are ignored." msgstr "" -#: ../../library/doctest.rst:1165 +#: ../../library/doctest.rst:1197 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:1204 msgid "Advanced API" msgstr "" -#: ../../library/doctest.rst:1174 +#: ../../library/doctest.rst:1206 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 +1977,97 @@ msgid "" "doctest's capabilities, then you should use the advanced API." msgstr "" -#: ../../library/doctest.rst:1179 +#: ../../library/doctest.rst:1211 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:1214 msgid "" ":class:`Example`: A single Python :term:`statement`, paired with its " "expected output." msgstr "" -#: ../../library/doctest.rst:1185 +#: ../../library/doctest.rst:1217 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:1220 msgid "" "Additional processing classes are defined to find, parse, and run, and check " "doctest examples:" msgstr "" -#: ../../library/doctest.rst:1191 +#: ../../library/doctest.rst:1223 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:1227 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:1230 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:1233 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:1236 msgid "" "The relationships among these processing classes are summarized in the " "following diagram::" msgstr "" -#: ../../library/doctest.rst:1220 +#: ../../library/doctest.rst:1239 +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:1252 msgid "DocTest Objects" msgstr "" -#: ../../library/doctest.rst:1225 +#: ../../library/doctest.rst:1257 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:1261 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:1267 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:1273 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 +2075,57 @@ msgid "" "`globs` after the test is run." msgstr "" -#: ../../library/doctest.rst:1249 +#: ../../library/doctest.rst:1281 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:1287 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 " +"``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:1294 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:1301 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:1308 msgid "Example Objects" msgstr "" -#: ../../library/doctest.rst:1281 +#: ../../library/doctest.rst:1313 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:1318 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:1324 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:1331 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 +2133,7 @@ msgid "" "The constructor adds a newline when necessary." msgstr "" -#: ../../library/doctest.rst:1307 +#: ../../library/doctest.rst:1339 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 +2142,20 @@ msgid "" "unless it's ``None``. The constructor adds a newline if needed." msgstr "" -#: ../../library/doctest.rst:1316 +#: ../../library/doctest.rst:1348 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:1355 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:1361 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 +2164,11 @@ msgid "" "default, no options are set." msgstr "" -#: ../../library/doctest.rst:1339 +#: ../../library/doctest.rst:1371 msgid "DocTestFinder objects" msgstr "" -#: ../../library/doctest.rst:1344 +#: ../../library/doctest.rst:1376 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 +2176,48 @@ msgid "" "classes, functions, methods, staticmethods, classmethods, and properties." msgstr "" -#: ../../library/doctest.rst:1349 +#: ../../library/doctest.rst:1381 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:1384 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:1387 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:1390 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:1394 msgid ":class:`DocTestFinder` defines the following method:" msgstr "" -#: ../../library/doctest.rst:1367 +#: ../../library/doctest.rst:1399 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:1402 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:1406 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 +2225,26 @@ msgid "" "module is used:" msgstr "" -#: ../../library/doctest.rst:1378 +#: ../../library/doctest.rst:1410 msgid "As a default namespace, if *globs* is not specified." msgstr "" -#: ../../library/doctest.rst:1380 +#: ../../library/doctest.rst:1412 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:1416 msgid "To find the name of the file containing the object." msgstr "" -#: ../../library/doctest.rst:1386 +#: ../../library/doctest.rst:1418 msgid "To help find the line number of the object within its file." msgstr "" -#: ../../library/doctest.rst:1388 +#: ../../library/doctest.rst:1420 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,44 +2253,44 @@ msgid "" "contained objects will (recursively) be searched for doctests." msgstr "" -#: ../../library/doctest.rst:1394 +#: ../../library/doctest.rst:1426 msgid "" "The globals for each :class:`DocTest` is formed by combining *globs* and " "*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new " -"shallow copy of the globals dictionary is created for each :class:`DocTest`. " -"If *globs* is not specified, then it defaults to the module's *__dict__*, if " -"specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it " -"defaults to ``{}``." +"shallow copy of the globals dictionary is created for each :class:`!" +"DocTest`. If *globs* is not specified, then it defaults to the module's :" +"attr:`~module.__dict__`, if specified, or ``{}`` otherwise. If *extraglobs* " +"is not specified, then it defaults to ``{}``." msgstr "" -#: ../../library/doctest.rst:1405 +#: ../../library/doctest.rst:1437 msgid "DocTestParser objects" msgstr "" -#: ../../library/doctest.rst:1410 +#: ../../library/doctest.rst:1442 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:1446 msgid ":class:`DocTestParser` defines the following methods:" msgstr "" -#: ../../library/doctest.rst:1419 +#: ../../library/doctest.rst:1451 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:1454 msgid "" "*globs*, *name*, *filename*, and *lineno* are attributes for the new :class:" -"`DocTest` object. See the documentation for :class:`DocTest` for more " +"`!DocTest` object. See the documentation for :class:`DocTest` for more " "information." msgstr "" -#: ../../library/doctest.rst:1429 +#: ../../library/doctest.rst:1461 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,51 +2298,51 @@ msgid "" "error messages." msgstr "" -#: ../../library/doctest.rst:1436 +#: ../../library/doctest.rst:1468 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 " -"the :class:`Example`\\ s are 0-based. The optional argument *name* is a " +"the :class:`!Example`\\ s are 0-based. The optional argument *name* is a " "name identifying this string, and is only used for error messages." msgstr "" -#: ../../library/doctest.rst:1443 +#: ../../library/doctest.rst:1475 msgid "TestResults objects" msgstr "" -#: ../../library/doctest.rst:1450 +#: ../../library/doctest.rst:1482 msgid "Number of failed tests." msgstr "" -#: ../../library/doctest.rst:1454 +#: ../../library/doctest.rst:1486 msgid "Number of attempted tests." msgstr "" -#: ../../library/doctest.rst:1458 +#: ../../library/doctest.rst:1490 msgid "Number of skipped tests." msgstr "" -#: ../../library/doctest.rst:1466 +#: ../../library/doctest.rst:1498 msgid "DocTestRunner objects" msgstr "" -#: ../../library/doctest.rst:1471 +#: ../../library/doctest.rst:1503 msgid "" "A processing class used to execute and verify the interactive examples in a :" "class:`DocTest`." msgstr "" -#: ../../library/doctest.rst:1474 +#: ../../library/doctest.rst:1506 msgid "" "The comparison between expected outputs and actual outputs is done by an :" "class:`OutputChecker`. This comparison may be customized with a number of " "option flags; see section :ref:`doctest-options` for more information. If " "the option flags are insufficient, then the comparison may also be " -"customized by passing a subclass of :class:`OutputChecker` to the " +"customized by passing a subclass of :class:`!OutputChecker` to the " "constructor." msgstr "" -#: ../../library/doctest.rst:1480 +#: ../../library/doctest.rst:1512 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 +2353,14 @@ msgid "" "`report_unexpected_exception`, and :meth:`report_failure`." msgstr "" -#: ../../library/doctest.rst:1488 +#: ../../library/doctest.rst:1520 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:1524 msgid "" "The optional keyword argument *verbose* controls the :class:" "`DocTestRunner`'s verbosity. If *verbose* is ``True``, then information is " @@ -1796,14 +2369,14 @@ msgid "" "verbose output is used iff the command-line switch ``-v`` is used." msgstr "" -#: ../../library/doctest.rst:1498 +#: ../../library/doctest.rst:1530 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:1534 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 +2384,53 @@ msgid "" "`summarize` methods return a :class:`TestResults` instance." msgstr "" -#: ../../library/doctest.rst:1507 +#: ../../library/doctest.rst:1539 msgid ":class:`DocTestRunner` defines the following methods:" msgstr "" -#: ../../library/doctest.rst:1512 +#: ../../library/doctest.rst:1544 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:1548 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:" +"containing *example*. *out* is the output function that was passed to :meth:" "`DocTestRunner.run`." msgstr "" -#: ../../library/doctest.rst:1523 +#: ../../library/doctest.rst:1555 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:1559 ../../library/doctest.rst:1570 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:1566 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:1577 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:1581 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 +2438,14 @@ msgid "" "output function that was passed to :meth:`DocTestRunner.run`." msgstr "" -#: ../../library/doctest.rst:1557 +#: ../../library/doctest.rst:1589 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:1593 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 +2453,54 @@ msgid "" "after the test completes, then use *clear_globs=False*." msgstr "" -#: ../../library/doctest.rst:1566 +#: ../../library/doctest.rst:1598 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:1602 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:1609 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:1612 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:1616 msgid ":class:`DocTestParser` has the following attributes:" msgstr "" -#: ../../library/doctest.rst:1588 +#: ../../library/doctest.rst:1620 msgid "Number of attempted examples." msgstr "" -#: ../../library/doctest.rst:1592 +#: ../../library/doctest.rst:1624 msgid "Number of failed examples." msgstr "" -#: ../../library/doctest.rst:1596 +#: ../../library/doctest.rst:1628 msgid "Number of skipped examples." msgstr "" -#: ../../library/doctest.rst:1604 +#: ../../library/doctest.rst:1636 msgid "OutputChecker objects" msgstr "" -#: ../../library/doctest.rst:1609 +#: ../../library/doctest.rst:1641 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 +2509,11 @@ msgid "" "string describing the differences between two outputs." msgstr "" -#: ../../library/doctest.rst:1616 +#: ../../library/doctest.rst:1648 msgid ":class:`OutputChecker` defines the following methods:" msgstr ":class:`OutputChecker` define os seguintes métodos:" -#: ../../library/doctest.rst:1620 +#: ../../library/doctest.rst:1652 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 +2522,28 @@ msgid "" "`doctest-options` for more information about option flags." msgstr "" -#: ../../library/doctest.rst:1629 +#: ../../library/doctest.rst:1661 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:1669 msgid "Debugging" msgstr "Depuração" -#: ../../library/doctest.rst:1639 +#: ../../library/doctest.rst:1671 msgid "Doctest provides several mechanisms for debugging doctest examples:" msgstr "" -#: ../../library/doctest.rst:1641 +#: ../../library/doctest.rst:1673 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:1676 msgid "" "The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that " "raises an exception for the first failing example, containing information " @@ -1978,13 +2551,13 @@ msgid "" "debugging on the example." msgstr "" -#: ../../library/doctest.rst:1649 +#: ../../library/doctest.rst:1681 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:1684 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 +2565,67 @@ msgid "" "`a.py` contains just this module docstring::" msgstr "" -#: ../../library/doctest.rst:1667 +#: ../../library/doctest.rst:1689 +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:1699 msgid "Then an interactive Python session may look like this::" msgstr "" -#: ../../library/doctest.rst:1700 +#: ../../library/doctest.rst:1701 +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:1732 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:1738 msgid "Convert text with examples to a script." msgstr "" -#: ../../library/doctest.rst:1708 +#: ../../library/doctest.rst:1740 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 +2633,46 @@ msgid "" "generated script is returned as a string. For example, ::" msgstr "" -#: ../../library/doctest.rst:1723 +#: ../../library/doctest.rst:1745 +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:1755 msgid "displays::" msgstr "" -#: ../../library/doctest.rst:1733 +#: ../../library/doctest.rst:1757 +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:1765 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:1772 msgid "Convert the doctest for an object to a script." msgstr "" -#: ../../library/doctest.rst:1742 +#: ../../library/doctest.rst:1774 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 +2682,23 @@ msgid "" "module :file:`a.py` contains a top-level function :func:`!f`, then ::" msgstr "" -#: ../../library/doctest.rst:1752 +#: ../../library/doctest.rst:1781 +msgid "" +"import a, doctest\n" +"print(doctest.testsource(a, \"a.f\"))" +msgstr "" + +#: ../../library/doctest.rst:1784 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:1790 msgid "Debug the doctests for an object." msgstr "" -#: ../../library/doctest.rst:1760 +#: ../../library/doctest.rst:1792 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 +2706,13 @@ msgid "" "the control of the Python debugger, :mod:`pdb`." msgstr "" -#: ../../library/doctest.rst:1765 +#: ../../library/doctest.rst:1797 msgid "" "A shallow copy of ``module.__dict__`` is used for both local and global " "execution context." msgstr "" -#: ../../library/doctest.rst:1768 +#: ../../library/doctest.rst:1800 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 +2724,30 @@ msgid "" "to :func:`pdb.run`." msgstr "" -#: ../../library/doctest.rst:1779 +#: ../../library/doctest.rst:1811 msgid "Debug the doctests in a string." msgstr "" -#: ../../library/doctest.rst:1781 +#: ../../library/doctest.rst:1813 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:1816 msgid "" "Optional argument *pm* has the same meaning as in function :func:`debug` " "above." msgstr "" -#: ../../library/doctest.rst:1786 +#: ../../library/doctest.rst:1818 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:1823 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 +2755,7 @@ msgid "" "(which is a doctest!) for more details:" msgstr "" -#: ../../library/doctest.rst:1799 +#: ../../library/doctest.rst:1831 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 +2765,89 @@ msgid "" "the actual output." msgstr "" -#: ../../library/doctest.rst:1806 +#: ../../library/doctest.rst:1838 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:1841 msgid "" "There are two exceptions that may be raised by :class:`DebugRunner` " "instances:" msgstr "" -#: ../../library/doctest.rst:1814 +#: ../../library/doctest.rst:1846 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:1850 msgid ":exc:`DocTestFailure` defines the following attributes:" msgstr "" -#: ../../library/doctest.rst:1823 ../../library/doctest.rst:1847 +#: ../../library/doctest.rst:1855 ../../library/doctest.rst:1879 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:1860 ../../library/doctest.rst:1884 msgid "The :class:`Example` that failed." msgstr "" -#: ../../library/doctest.rst:1833 +#: ../../library/doctest.rst:1865 msgid "The example's actual output." msgstr "" -#: ../../library/doctest.rst:1838 +#: ../../library/doctest.rst:1870 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:1874 msgid ":exc:`UnexpectedException` defines the following attributes:" msgstr ":exc:`UnexpectedException` define os seguintes atributos:" -#: ../../library/doctest.rst:1857 +#: ../../library/doctest.rst:1889 msgid "" "A tuple containing information about the unexpected exception, as returned " "by :func:`sys.exc_info`." msgstr "" -#: ../../library/doctest.rst:1864 +#: ../../library/doctest.rst:1896 msgid "Soapbox" msgstr "" -#: ../../library/doctest.rst:1866 +#: ../../library/doctest.rst:1898 msgid "" "As mentioned in the introduction, :mod:`doctest` has grown to have three " "primary uses:" msgstr "" -#: ../../library/doctest.rst:1869 +#: ../../library/doctest.rst:1901 msgid "Checking examples in docstrings." msgstr "" -#: ../../library/doctest.rst:1871 +#: ../../library/doctest.rst:1903 msgid "Regression testing." msgstr "" -#: ../../library/doctest.rst:1873 +#: ../../library/doctest.rst:1905 msgid "Executable documentation / literate testing." msgstr "" -#: ../../library/doctest.rst:1875 +#: ../../library/doctest.rst:1907 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:1911 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 +2859,7 @@ msgid "" "\"harmless\" change." msgstr "" -#: ../../library/doctest.rst:1887 +#: ../../library/doctest.rst:1919 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 +2880,13 @@ msgid "" "different results, blurring the distinction between testing and explaining." msgstr "" -#: ../../library/doctest.rst:1905 +#: ../../library/doctest.rst:1937 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:1940 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 +2894,7 @@ msgid "" "doctest." msgstr "" -#: ../../library/doctest.rst:1913 +#: ../../library/doctest.rst:1945 msgid "" "Define functions named ``_regrtest_topic`` that consist of single " "docstrings, containing test cases for the named topics. These functions can " @@ -2253,13 +2902,13 @@ msgid "" "test file." msgstr "" -#: ../../library/doctest.rst:1917 +#: ../../library/doctest.rst:1949 msgid "" -"Define a ``__test__`` dictionary mapping from regression test topics to " -"docstrings containing test cases." +"Define a :attr:`~module.__test__` dictionary mapping from regression test " +"topics to docstrings containing test cases." msgstr "" -#: ../../library/doctest.rst:1920 +#: ../../library/doctest.rst:1952 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 +2916,71 @@ msgid "" "example of such a test runner::" msgstr "" -#: ../../library/doctest.rst:1942 +#: ../../library/doctest.rst:1957 +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:1974 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/doctest.rst:1943 +#: ../../library/doctest.rst:1975 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:383 msgid ">>>" msgstr ">>>" -#: ../../library/doctest.rst:339 +#: ../../library/doctest.rst:383 msgid "interpreter prompt" -msgstr "" +msgstr "prompt do interpretador" -#: ../../library/doctest.rst:339 ../../library/doctest.rst:577 +#: ../../library/doctest.rst:383 ../../library/doctest.rst:618 msgid "..." msgstr "..." -#: ../../library/doctest.rst:505 +#: ../../library/doctest.rst:549 msgid "^ (caret)" msgstr "^ (circunflexo)" -#: ../../library/doctest.rst:505 +#: ../../library/doctest.rst:549 msgid "marker" msgstr "" -#: ../../library/doctest.rst:557 +#: ../../library/doctest.rst:598 msgid "" msgstr "" -#: ../../library/doctest.rst:577 ../../library/doctest.rst:707 +#: ../../library/doctest.rst:618 ../../library/doctest.rst:743 msgid "in doctests" msgstr "" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:743 msgid "# (hash)" msgstr "# (cerquilha)" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:743 msgid "+ (plus)" msgstr "+ (mais)" -#: ../../library/doctest.rst:707 +#: ../../library/doctest.rst:743 msgid "- (minus)" msgstr "- (menos)" diff --git a/library/email.charset.po b/library/email.charset.po index b7dd7e376..8a55e69ce 100644 --- a/library/email.charset.po +++ b/library/email.charset.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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +37,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 +54,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 +76,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 +89,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 +105,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 +127,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 +138,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 +150,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 +161,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 +172,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 +181,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 +203,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 +215,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 +254,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 +332,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 +345,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 +358,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 +402,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..034637206 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 "" @@ -215,8 +233,8 @@ msgstr "" #: ../../library/email.compat32-message.rst:183 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by :meth:`~email.message.EmailMessage." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by :meth:`~email.message.EmailMessage." "set_content` and the related ``make`` and ``add`` methods." msgstr "" @@ -267,13 +285,10 @@ msgstr "" #: ../../library/email.compat32-message.rst:226 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by :meth:`~email.message.EmailMessage." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by :meth:`~email.message.EmailMessage." "get_content` and :meth:`~email.message.EmailMessage.iter_parts`." msgstr "" -"Esse é um método legado. Na classe :class:`~email.emailmessage.EmailMessage` " -"sua funcionalidade é substituída por :meth:`~email.message.EmailMessage." -"get_content` e :meth:`~email.message.EmailMessage.iter_parts`." #: ../../library/email.compat32-message.rst:234 msgid "" @@ -284,8 +299,8 @@ msgstr "" #: ../../library/email.compat32-message.rst:238 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by :meth:`~email.message.EmailMessage." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by :meth:`~email.message.EmailMessage." "set_content`." msgstr "" @@ -319,9 +334,9 @@ msgstr "" #: ../../library/email.compat32-message.rst:267 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by the *charset* parameter of the :meth:" -"`email.emailmessage.EmailMessage.set_content` method." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by the *charset* parameter of the :meth:`email." +"message.EmailMessage.set_content` method." msgstr "" #: ../../library/email.compat32-message.rst:275 @@ -332,8 +347,8 @@ msgstr "" #: ../../library/email.compat32-message.rst:278 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class it always returns ``None``." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"it always returns ``None``." msgstr "" #: ../../library/email.compat32-message.rst:283 @@ -380,6 +395,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 +429,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 +503,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 " @@ -561,9 +607,9 @@ msgstr "" #: ../../library/email.compat32-message.rst:488 #: ../../library/email.compat32-message.rst:526 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by the *params* property of the " -"individual header objects returned by the header access methods." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by the *params* property of the individual " +"header objects returned by the header access methods." msgstr "" #: ../../library/email.compat32-message.rst:496 @@ -599,6 +645,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 " @@ -674,8 +726,8 @@ msgstr "" #: ../../library/email.compat32-message.rst:581 msgid "" -"This is a legacy method. On the :class:`~email.emailmessage.EmailMessage` " -"class its functionality is replaced by the ``make_`` and ``add_`` methods." +"This is a legacy method. On the :class:`~email.message.EmailMessage` class " +"its functionality is replaced by the ``make_`` and ``add_`` methods." msgstr "" #: ../../library/email.compat32-message.rst:588 @@ -766,6 +818,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 +839,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..6f2389a8a 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0ac5c9f19 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c460a8074 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..5a39fcc88 100644 --- a/library/email.examples.po +++ b/library/email.examples.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +45,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 +102,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 +166,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 +230,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 +409,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 +534,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 +662,207 @@ 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 "" +"import os\n" +"import sys\n" +"import tempfile\n" +"import mimetypes\n" +"import webbrowser\n" +"\n" +"# Importa os módulos de e-mail que precisaremos\n" +"from email import policy\n" +"from email.parser import BytesParser\n" +"\n" +"\n" +"def magic_html_parser(html_text, partfiles):\n" +" \"\"\"Retorna HTML com segurança e link para partfiles.\n" +"\n" +" Reescreve os atributos href=\"cid:....\" para apontar aos arquivos em " +"partfiles.\n" +" Embora não seja trivial, isso deve ser possível usando html.parser.\n" +" \"\"\"\n" +" raise NotImplementedError(\"Add the magic needed\")\n" +"\n" +"\n" +"# Em um programa real, você pegaria o nome de arquivo a partir dos " +"argumentos.\n" +"with open('outgoing.msg', 'rb') as fp:\n" +" msg = BytesParser(policy=policy.default).parse(fp)\n" +"\n" +"# Agora os itens de cabeçalho podem ser acessados como um dicionário e\n" +"# qualquer caractere não-ASCII será convertido para unicode:\n" +"print('To:', msg['to'])\n" +"print('From:', msg['from'])\n" +"print('Subject:', msg['subject'])\n" +"\n" +"# Se quisermos imprimir uma prévia do conteúdo da mensagem, podemos\n" +"# extrair o conteúdo menos formatado e imprimir as três primeiras linhas.\n" +"# É claro que, se a mensagem não tiver uma parte de texto simples,\n" +"# imprimir as três primeiras linhas de HTML provavelmente será inútil,\n" +"# mas este é apenas um exemplo conceitual.\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" +"# Podemos extrair a alternativa richest para exibi-la:\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" +" # remove novamente o <> para ir da forma email de cid para " +"html.\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" +"# É claro que há muitas mensagens de e-mail que podem quebrar\n" +"# esse simples programa, mas ele lidará com as mais comuns.\n" + #: ../../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..1cb8533f6 100644 --- a/library/email.generator.po +++ b/library/email.generator.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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +41,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 +64,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 +87,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 +101,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 +112,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 +130,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 +147,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 +160,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 +185,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 +204,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 +226,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 +239,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 +257,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 +269,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 +285,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 +301,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 +312,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 +328,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 +361,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 +373,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 +387,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 +402,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 +478,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..8351688dd 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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-" @@ -262,33 +272,68 @@ msgid "" msgstr "" #: ../../library/email.header.rst:181 +msgid "For historical reasons, this function may return either:" +msgstr "" + +#: ../../library/email.header.rst:183 msgid "" -"This function returns a list of ``(decoded_string, charset)`` pairs " -"containing each of the decoded parts of the header. *charset* is ``None`` " -"for non-encoded parts of the header, otherwise a lower case string " -"containing the name of the character set specified in the encoded string." +"A list of pairs containing each of the decoded parts of the header, " +"``(decoded_bytes, charset)``, where *decoded_bytes* is always an instance " +"of :class:`bytes`, and *charset* is either:" +msgstr "" + +#: ../../library/email.header.rst:187 +msgid "A lower case string containing the name of the character set specified." msgstr "" -#: ../../library/email.header.rst:186 -msgid "Here's an example::" -msgstr "Aqui está um exemplo::" +#: ../../library/email.header.rst:189 +msgid "``None`` for non-encoded parts of the header." +msgstr "" -#: ../../library/email.header.rst:195 +#: ../../library/email.header.rst:191 +msgid "" +"A list of length 1 containing a pair ``(string, None)``, where *string* is " +"always an instance of :class:`str`." +msgstr "" + +#: ../../library/email.header.rst:194 +msgid "" +"An :exc:`email.errors.HeaderParseError` may be raised when certain decoding " +"errors occur (e.g. a base64 decoding exception)." +msgstr "" + +#: ../../library/email.header.rst:197 +msgid "Here are examples:" +msgstr "" + +#: ../../library/email.header.rst:209 +msgid "" +"This function exists for backwards compatibility only. For new code, we " +"recommend using :class:`email.headerregistry.HeaderRegistry`." +msgstr "" + +#: ../../library/email.header.rst:215 msgid "" "Create a :class:`Header` instance from a sequence of pairs as returned by :" "func:`decode_header`." msgstr "" -#: ../../library/email.header.rst:198 +#: ../../library/email.header.rst:218 msgid "" ":func:`decode_header` takes a header value string and returns a sequence of " "pairs of the format ``(decoded_string, charset)`` where *charset* is the " "name of the character set." msgstr "" -#: ../../library/email.header.rst:202 +#: ../../library/email.header.rst:222 msgid "" "This function takes one of those sequence of pairs and returns a :class:" "`Header` instance. Optional *maxlinelen*, *header_name*, and " "*continuation_ws* are as in the :class:`Header` constructor." msgstr "" + +#: ../../library/email.header.rst:228 +msgid "" +"This function exists for backwards compatibility only, and is not " +"recommended for use in new code." +msgstr "" diff --git a/library/email.headerregistry.po b/library/email.headerregistry.po index b1a5a3d01..d5e65b964 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..789eac55c 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..67c198231 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..708a39000 100644 --- a/library/email.mime.po +++ b/library/email.mime.po @@ -1,31 +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: -# Rafael Fontenelle , 2021 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +56,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 +215,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 +231,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 +277,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* contém 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 +323,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 +345,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 +375,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 +405,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 +427,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..d88d588ef 100644 --- a/library/email.parser.po +++ b/library/email.parser.po @@ -1,26 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +142,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``." @@ -169,7 +169,7 @@ msgid "" "Works like :class:`BytesFeedParser` except that the input to the :meth:" "`~BytesFeedParser.feed` method must be a string. This is of limited " "utility, since the only way for such a message to be valid is for it to " -"contain only ASCII text or, if :attr:`~email.policy.Policy.utf8` is " +"contain only ASCII text or, if :attr:`~email.policy.EmailPolicy.utf8` is " "``True``, no binary attachments." msgstr "" @@ -219,11 +219,11 @@ msgstr "" #: ../../library/email.parser.rst:161 msgid "" "The bytes contained in *fp* must be formatted as a block of :rfc:`5322` (or, " -"if :attr:`~email.policy.Policy.utf8` is ``True``, :rfc:`6532`) style headers " -"and header continuation lines, optionally preceded by an envelope header. " -"The header block is terminated either by the end of the data or by a blank " -"line. Following the header block is the body of the message (which may " -"contain MIME-encoded subparts, including subparts with a :mailheader:" +"if :attr:`~email.policy.EmailPolicy.utf8` is ``True``, :rfc:`6532`) style " +"headers and header continuation lines, optionally preceded by an envelope " +"header. The header block is terminated either by the end of the data or by " +"a blank line. Following the header block is the body of the message (which " +"may contain MIME-encoded subparts, including subparts with a :mailheader:" "`Content-Transfer-Encoding` of ``8bit``)." msgstr "" @@ -333,6 +333,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..63aa71660 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..805ab0a52 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c1a5e6e52 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..27f2a129d 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..df64c2ca2 100644 --- a/library/enum.po +++ b/library/enum.po @@ -1,35 +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: -# Marco Rougeth , 2021 -# Hildeberto Abreu Magalhães , 2022 -# Raphael Mendonça, 2022 -# Misael borges , 2022 -# Rafael Fontenelle , 2023 +# python-doc bot, 2025 +# 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-10-03 14:59+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +37,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 +115,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 +149,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 +209,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 +235,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,759 +249,1271 @@ 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 -msgid "This method is called in two different ways:" +#: ../../library/enum.rst:180 +msgid "" +"Before 3.11 ``EnumType`` was called ``EnumMeta``, which is still available " +"as an alias." msgstr "" +"Antes da versão 3.11, ``EnumType`` era chamado de ``EnumMeta``, que ainda " +"está disponível como um apelido." -#: ../../library/enum.rst:177 +#: ../../library/enum.rst:184 +msgid "This method is called in two different ways:" +msgstr "Este método é chamado de formas diferentes:" + +#: ../../library/enum.rst:186 msgid "to look up an existing member:" -msgstr "" +msgstr "para procurar um membro existente:" #: ../../library/enum.rst:0 msgid "cls" -msgstr "" +msgstr "cls" -#: ../../library/enum.rst:179 ../../library/enum.rst:185 +#: ../../library/enum.rst:188 ../../library/enum.rst:194 msgid "The enum class being called." -msgstr "" +msgstr "A classe enum sendo chamada." #: ../../library/enum.rst:0 msgid "value" -msgstr "value" +msgstr "valor" -#: ../../library/enum.rst:180 +#: ../../library/enum.rst:189 msgid "The value to lookup." -msgstr "" +msgstr "O valor para procurar." -#: ../../library/enum.rst:182 +#: ../../library/enum.rst:191 msgid "" "to use the ``cls`` enum to create a new enum (only if the existing enum does " "not have any members):" msgstr "" +"para usar a enumeração ``cls`` para criar uma nova enumeração (somente se a " +"enumeração existente não tiver nenhum membro):" -#: ../../library/enum.rst:186 +#: ../../library/enum.rst:195 msgid "The name of the new Enum to create." -msgstr "" +msgstr "O nome do novo Enum para criar." #: ../../library/enum.rst:0 msgid "names" msgstr "nomes" -#: ../../library/enum.rst:187 +#: ../../library/enum.rst:196 msgid "The names/values of the members for the new Enum." -msgstr "" +msgstr "Os nomes/valores dos membros para o novo Enum." #: ../../library/enum.rst:0 msgid "module" msgstr "módulo" -#: ../../library/enum.rst:188 +#: ../../library/enum.rst:197 msgid "The name of the module the new Enum is created in." -msgstr "" +msgstr "O nome do módulo no qual o novo Enum é criado." #: ../../library/enum.rst:0 msgid "qualname" msgstr "qualname" -#: ../../library/enum.rst:189 +#: ../../library/enum.rst:198 msgid "The actual location in the module where this Enum can be found." -msgstr "" +msgstr "O local real no módulo onde este Enum pode ser encontrado." #: ../../library/enum.rst:0 msgid "type" msgstr "tipo" -#: ../../library/enum.rst:190 +#: ../../library/enum.rst:199 msgid "A mix-in type for the new Enum." -msgstr "" +msgstr "Um tipo de mix-in para o novo Enum." #: ../../library/enum.rst:0 msgid "start" msgstr "start" -#: ../../library/enum.rst:191 +#: ../../library/enum.rst:200 msgid "The first integer value for the Enum (used by :class:`auto`)." -msgstr "" +msgstr "O primeiro valor inteiro para o Enum (usado por :class:`auto`)." #: ../../library/enum.rst:0 msgid "boundary" -msgstr "" +msgstr "boundary" -#: ../../library/enum.rst:192 +#: ../../library/enum.rst:201 msgid "" "How to handle out-of-range values from bit operations (:class:`Flag` only)." msgstr "" +"Como lidar com valores fora do intervalo de operações de bits (somente :" +"class:`Flag`)." -#: ../../library/enum.rst:196 +#: ../../library/enum.rst:205 msgid "Returns ``True`` if member belongs to the ``cls``::" +msgstr "Retorna ``True`` se o membro pertencer a ``cls``::" + +#: ../../library/enum.rst:207 +msgid "" +">>> some_var = Color.RED\n" +">>> some_var in Color\n" +"True\n" +">>> Color.RED.value in Color\n" +"True" msgstr "" +">>> some_var = Color.RED\n" +">>> some_var in Color\n" +"True\n" +">>> Color.RED.value in Color\n" +"True" -#: ../../library/enum.rst:206 +#: ../../library/enum.rst:215 msgid "" "Before Python 3.12, a ``TypeError`` is raised if a non-Enum-member is used " "in a containment check." msgstr "" +"Antes do Python 3.12, um ``TypeError`` era levantado se um membro não Enum " +"fosse usado em uma verificação de contenção." -#: ../../library/enum.rst:211 +#: ../../library/enum.rst:220 msgid "" "Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the " "names of the members in *cls*::" msgstr "" +"Retorna ``['__class__', '__doc__', '__members__', '__module__']`` e os nomes " +"dos membros em *cls*::" -#: ../../library/enum.rst:219 +#: ../../library/enum.rst:223 +msgid "" +">>> dir(Color)\n" +"['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', " +"'__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', " +"'__module__', '__name__', '__qualname__']" +msgstr "" +">>> dir(Color)\n" +"['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', " +"'__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', " +"'__module__', '__name__', '__qualname__']" + +#: ../../library/enum.rst:228 msgid "" "Returns the Enum member in *cls* matching *name*, or raises a :exc:" "`KeyError`::" msgstr "" +"Retorna o membro Enum em *cls* correspondente a *name* ou levanta :exc:" +"`KeyError`::" + +#: ../../library/enum.rst:230 +msgid "" +">>> Color['BLUE']\n" +"" +msgstr "" +">>> Color['BLUE']\n" +"" -#: ../../library/enum.rst:226 +#: ../../library/enum.rst:235 msgid "Returns each member in *cls* in definition order::" +msgstr "Retorna cada membro em *cls* na ordem de definição::" + +#: ../../library/enum.rst:237 +msgid "" +">>> list(Color)\n" +"[, , ]" msgstr "" +">>> list(Color)\n" +"[, , ]" -#: ../../library/enum.rst:233 +#: ../../library/enum.rst:242 msgid "Returns the number of member in *cls*::" +msgstr "Retorna o número de membros em *cls*::" + +#: ../../library/enum.rst:244 +msgid "" +">>> len(Color)\n" +"3" msgstr "" +">>> len(Color)\n" +"3" -#: ../../library/enum.rst:240 +#: ../../library/enum.rst:249 msgid "Returns a mapping of every enum name to its member, including aliases" msgstr "" +"Retorna um mapeamento de cada nome de enumeração para seu membro, incluindo " +"apelidos" -#: ../../library/enum.rst:244 +#: ../../library/enum.rst:253 msgid "Returns each member in *cls* in reverse definition order::" -msgstr "" +msgstr "Retorna cada membro em *cls* na ordem inversa de definição::" -#: ../../library/enum.rst:251 +#: ../../library/enum.rst:255 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 -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." +">>> list(reversed(Color))\n" +"[, , ]" msgstr "" +">>> list(reversed(Color))\n" +"[, , ]" #: ../../library/enum.rst:261 -msgid "" -"Before 3.11 ``EnumType`` was called ``EnumMeta``, which is still available " -"as an alias." -msgstr "" - -#: ../../library/enum.rst:266 msgid "*Enum* is the base class for all *enum* enumerations." -msgstr "" +msgstr "*Enum* é a classe base para todas as enumerações *enum*." -#: ../../library/enum.rst:270 +#: ../../library/enum.rst:265 msgid "The name used to define the ``Enum`` member::" +msgstr "O nome usado para definir o membro ``Enum``::" + +#: ../../library/enum.rst:267 +msgid "" +">>> Color.BLUE.name\n" +"'BLUE'" msgstr "" +">>> Color.BLUE.name\n" +"'BLUE'" -#: ../../library/enum.rst:277 +#: ../../library/enum.rst:272 msgid "The value given to the ``Enum`` member::" +msgstr "O valor dado ao membro ``Enum``::" + +#: ../../library/enum.rst:274 +msgid "" +">>> Color.RED.value\n" +"1" msgstr "" +">>> Color.RED.value\n" +"1" -#: ../../library/enum.rst:282 ../../library/enum.rst:302 +#: ../../library/enum.rst:277 ../../library/enum.rst:297 msgid "Value of the member, can be set in :meth:`~Enum.__new__`." -msgstr "" +msgstr "O valor do membro pode ser definido em :meth:`~Enum.__new__`." -#: ../../library/enum.rst:284 +#: ../../library/enum.rst:279 msgid "Enum member values" -msgstr "" +msgstr "Valores de membros de Enum" -#: ../../library/enum.rst:286 +#: ../../library/enum.rst:281 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 "" +"Os valores dos membros podem ser qualquer coisa: :class:`int`, :class:`str`, " +"etc. Se o valor exato não for importante, você pode usar instâncias de :" +"class:`auto` e um valor apropriado será escolhido para você. Consulte :class:" +"`auto` para obter detalhes." -#: ../../library/enum.rst:291 +#: ../../library/enum.rst:286 msgid "" "While mutable/unhashable values, such as :class:`dict`, :class:`list` or a " "mutable :class:`~dataclasses.dataclass`, can be used, they will have a " "quadratic performance impact during creation relative to the total number of " "mutable/unhashable values in the enum." msgstr "" +"Embora valores mutáveis/não hasheáveis, como :class:`dict`, :class:`list` ou " +"um mutável :class:`~dataclasses.dataclass`, possam ser usados, eles terão um " +"impacto quadrático no desempenho durante a criação em relação ao número " +"total de valores mutáveis/não hasheáveis na enumeração." -#: ../../library/enum.rst:298 +#: ../../library/enum.rst:293 msgid "Name of the member." -msgstr "" +msgstr "Nome do membro." -#: ../../library/enum.rst:306 +#: ../../library/enum.rst:301 msgid "" "No longer used, kept for backward compatibility. (class attribute, removed " "during class creation)." msgstr "" +"Não é mais usado, mantido para compatibilidade com versões anteriores. " +"(atributo de classe, removido durante a criação da classe)." -#: ../../library/enum.rst:311 +#: ../../library/enum.rst:306 msgid "" "``_ignore_`` is only used during creation and is removed from the " "enumeration once creation is complete." msgstr "" +"``_ignore_`` é usado somente durante a criação e é removido da enumeração " +"quando a criação é concluída." -#: ../../library/enum.rst:314 +#: ../../library/enum.rst:309 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 "" +"``_ignore_`` é uma lista de nomes que não se tornarão membros e cujos nomes " +"também serão removidos da enumeração concluída. Veja :ref:`TimePeriod ` para um exemplo." -#: ../../library/enum.rst:320 +#: ../../library/enum.rst:315 msgid "" "Returns ``['__class__', '__doc__', '__module__', 'name', 'value']`` and any " "public methods defined on *self.__class__*::" msgstr "" +"Retorna ``['__class__', '__doc__', '__module__', 'name', 'value']`` e " +"quaisquer métodos públicos definidos em *self.__class__*::" + +#: ../../library/enum.rst:318 +msgid "" +">>> from enum import Enum\n" +">>> 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 "" +">>> from enum import Enum\n" +">>> 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']" #: ../../library/enum.rst:0 msgid "name" msgstr "nome" -#: ../../library/enum.rst:341 +#: ../../library/enum.rst:337 msgid "The name of the member being defined (e.g. 'RED')." -msgstr "" +msgstr "O nome do membro que está sendo definido (por exemplo, 'RED')." -#: ../../library/enum.rst:342 +#: ../../library/enum.rst:338 msgid "The start value for the Enum; the default is 1." -msgstr "" +msgstr "O valor inicial do Enum; o padrão é 1." #: ../../library/enum.rst:0 msgid "count" msgstr "" -#: ../../library/enum.rst:343 +#: ../../library/enum.rst:339 msgid "The number of members currently defined, not including this one." -msgstr "" +msgstr "O número de membros atualmente definido, sem incluir este." #: ../../library/enum.rst:0 msgid "last_values" msgstr "" -#: ../../library/enum.rst:344 +#: ../../library/enum.rst:340 msgid "A list of the previous values." -msgstr "" +msgstr "Uma lista de valores anteriores." -#: ../../library/enum.rst:346 +#: ../../library/enum.rst:342 msgid "" "A *staticmethod* that is used to determine the next value returned by :class:" "`auto`::" msgstr "" - -#: ../../library/enum.rst:362 +"Um *staticmethod* que é usado para determinar o próximo valor retornado por :" +"class:`auto`::" + +#: ../../library/enum.rst:345 +msgid "" +">>> from enum import auto, Enum\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 "" +">>> from enum import auto, Enum\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" + +#: ../../library/enum.rst:358 msgid "" "By default, does nothing. If multiple values are given in the member " "assignment, those values become separate arguments to ``__init__``; e.g." msgstr "" +"Por padrão, não faz nada. Se vários valores forem fornecidos na atribuição " +"de membro, esses valores se tornarão argumentos separados para ``__init__``; " +"por exemplo.:" -#: ../../library/enum.rst:369 +#: ../../library/enum.rst:365 msgid "" "``Weekday.__init__()`` would be called as ``Weekday.__init__(self, 1, " "'Mon')``" msgstr "" +"``Weekday.__init__()`` seria chamado como ``Weekday.__init__(self, 1, " +"'Mon')``" -#: ../../library/enum.rst:373 +#: ../../library/enum.rst:369 msgid "" "A *classmethod* that is used to further configure subsequent subclasses. By " "default, does nothing." msgstr "" +"Um *classmethod* usado para configurar subclasses subsequentes. Por padrão, " +"não faz nada." -#: ../../library/enum.rst:378 +#: ../../library/enum.rst:374 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 +"Um *classmethod* para procurar valores não encontrados em *cls*. Por padrão, " +"ele não faz nada, mas pode ser substituído para implementar um comportamento " +"de pesquisa personalizado::" + +#: ../../library/enum.rst:377 +msgid "" +">>> from enum import auto, 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 "" +">>> from enum import auto, 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" +"" + +#: ../../library/enum.rst:396 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:404 msgid "" "results in the call ``int('1a', 16)`` and a value of ``26`` for the member." msgstr "" -#: ../../library/enum.rst:412 +#: ../../library/enum.rst:408 msgid "" "When writing a custom ``__new__``, do not use ``super().__new__`` -- call " "the appropriate ``__new__`` instead." msgstr "" -#: ../../library/enum.rst:417 +#: ../../library/enum.rst:413 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:416 +msgid "" +">>> from enum import auto, Enum\n" +">>> 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:430 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:433 +msgid "" +">>> from enum import auto, Enum\n" +">>> 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:446 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:449 +msgid "" +">>> from enum import auto, Enum\n" +">>> 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:462 msgid "" "Using :class:`auto` with :class:`Enum` results in integers of increasing " "value, starting with ``1``." msgstr "" -#: ../../library/enum.rst:466 +#: ../../library/enum.rst:465 msgid "Added :ref:`enum-dataclass-support`" msgstr "" +#: ../../library/enum.rst:469 +msgid "Adds a new name as an alias to an existing member::" +msgstr "" + #: ../../library/enum.rst:471 msgid "" +">>> Color.RED._add_alias_(\"ERROR\")\n" +">>> Color.ERROR\n" +"" +msgstr "" + +#: ../../library/enum.rst:475 +msgid "" +"Raises a :exc:`NameError` if the name is already assigned to a different " +"member." +msgstr "" + +#: ../../library/enum.rst:481 +msgid "Adds a new value as an alias to an existing member::" +msgstr "" + +#: ../../library/enum.rst:483 +msgid "" +">>> Color.RED._add_value_alias_(42)\n" +">>> Color(42)\n" +"" +msgstr "" + +#: ../../library/enum.rst:487 +msgid "" +"Raises a :exc:`ValueError` if the value is already linked with a different " +"member." +msgstr "" + +#: ../../library/enum.rst:494 +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 " "operation is performed with an *IntEnum* member, the resulting value loses " "its enumeration status." msgstr "" -#: ../../library/enum.rst:492 +#: ../../library/enum.rst:515 msgid "" "Using :class:`auto` with :class:`IntEnum` results in integers of increasing " "value, starting with ``1``." msgstr "" -#: ../../library/enum.rst:495 +#: ../../library/enum.rst:518 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:525 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 " -"result of any string operation performed on or with a *StrEnum* member is " -"not part of the enumeration." +"*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 result " +"of any string operation performed on or with a *StrEnum* member is not part " +"of the enumeration." msgstr "" -#: ../../library/enum.rst:508 +#: ../../library/enum.rst:546 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 " "``isinstance(unknown, str)``), and in those locations you will need to use " -"``str(StrEnum.member)``." +"``str(MyStrEnum.MY_MEMBER)``." msgstr "" -#: ../../library/enum.rst:515 +#: ../../library/enum.rst:553 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:558 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:566 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:572 msgid "Returns *True* if value is in self::" msgstr "" -#: ../../library/enum.rst:555 +#: ../../library/enum.rst:574 +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:593 msgid "Returns all contained non-alias members::" msgstr "" -#: ../../library/enum.rst:566 +#: ../../library/enum.rst:595 +msgid "" +">>> list(Color.RED)\n" +"[]\n" +">>> list(purple)\n" +"[, ]" +msgstr "" + +#: ../../library/enum.rst:604 msgid "Returns number of members in flag::" msgstr "" -#: ../../library/enum.rst:577 +#: ../../library/enum.rst:606 +msgid "" +">>> len(Color.GREEN)\n" +"1\n" +">>> len(white)\n" +"3" +msgstr "" + +#: ../../library/enum.rst:615 msgid "Returns *True* if any members in flag, *False* otherwise::" msgstr "" -#: ../../library/enum.rst:589 +#: ../../library/enum.rst:617 +msgid "" +">>> bool(Color.GREEN)\n" +"True\n" +">>> bool(white)\n" +"True\n" +">>> black = Color(0)\n" +">>> bool(black)\n" +"False" +msgstr "" + +#: ../../library/enum.rst:627 msgid "Returns current flag binary or'ed with other::" msgstr "" -#: ../../library/enum.rst:596 +#: ../../library/enum.rst:629 +msgid "" +">>> Color.RED | Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:634 msgid "Returns current flag binary and'ed with other::" msgstr "" -#: ../../library/enum.rst:605 +#: ../../library/enum.rst:636 +msgid "" +">>> purple & white\n" +"\n" +">>> purple & Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:643 msgid "Returns current flag binary xor'ed with other::" msgstr "" -#: ../../library/enum.rst:614 +#: ../../library/enum.rst:645 +msgid "" +">>> purple ^ white\n" +"\n" +">>> purple ^ Color.GREEN\n" +"" +msgstr "" + +#: ../../library/enum.rst:652 msgid "Returns all the flags in *type(self)* that are not in *self*::" msgstr "" -#: ../../library/enum.rst:625 +#: ../../library/enum.rst:654 +msgid "" +">>> ~white\n" +"\n" +">>> ~purple\n" +"\n" +">>> ~Color.RED\n" +"" +msgstr "" + +#: ../../library/enum.rst:663 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:668 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:671 msgid "The *repr()* of zero-valued flags has changed. It is now::" msgstr "" -#: ../../library/enum.rst:641 +#: ../../library/enum.rst:679 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:693 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:696 +msgid "" +">>> Color.RED + 2\n" +"3" +msgstr "" + +#: ../../library/enum.rst:699 msgid "If a :class:`Flag` operation is performed with an *IntFlag* member and:" msgstr "" -#: ../../library/enum.rst:663 +#: ../../library/enum.rst:701 msgid "the result is a valid *IntFlag*: an *IntFlag* is returned" msgstr "" -#: ../../library/enum.rst:664 +#: ../../library/enum.rst:702 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:704 +msgid "The :func:`repr` of unnamed zero-valued flags has changed. It is now:" msgstr "" -#: ../../library/enum.rst:673 +#: ../../library/enum.rst:711 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:716 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:720 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:726 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:729 msgid ":meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag`" msgstr "" -#: ../../library/enum.rst:692 +#: ../../library/enum.rst:730 msgid ":meth:`!str.__str__` for :class:`StrEnum`" msgstr "" -#: ../../library/enum.rst:694 +#: ../../library/enum.rst:732 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:741 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:746 msgid "Ensure that each value has only one name::" msgstr "" -#: ../../library/enum.rst:724 +#: ../../library/enum.rst:748 +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:762 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:765 +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:777 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:780 +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:794 msgid "" "CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members." msgstr "" -#: ../../library/enum.rst:762 +#: ../../library/enum.rst:800 msgid "" "``FlagBoundary`` controls how out-of-range values are handled in :class:" "`Flag` and its subclasses." msgstr "" -#: ../../library/enum.rst:767 +#: ../../library/enum.rst:805 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:808 +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:823 msgid "" "Out-of-range values have invalid values removed, leaving a valid :class:" "`Flag` value::" msgstr "" -#: ../../library/enum.rst:799 +#: ../../library/enum.rst:826 +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:837 msgid "" "Out-of-range values lose their :class:`Flag` membership and revert to :class:" "`int`." msgstr "" -#: ../../library/enum.rst:812 +#: ../../library/enum.rst:850 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:853 +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:866 +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:873 +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:880 +msgid "A list of member names." +msgstr "" + +#: ../../library/enum.rst:887 msgid "Supported ``__dunder__`` names" msgstr "Nomes ``__dunder__`` suportados" -#: ../../library/enum.rst:831 +#: ../../library/enum.rst:889 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:892 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:898 msgid "Supported ``_sunder_`` names" msgstr "Nomes ``_sunder_`` suportados" -#: ../../library/enum.rst:842 -msgid "" -":meth:`~EnumType._add_alias_` -- adds a new name as an alias to an existing " -"member." -msgstr "" - -#: ../../library/enum.rst:844 -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:900 msgid ":attr:`~Enum._name_` -- name of the member" msgstr "" -#: ../../library/enum.rst:847 +#: ../../library/enum.rst:901 msgid ":attr:`~Enum._value_` -- value of the member; can be set in ``__new__``" msgstr "" -#: ../../library/enum.rst:848 +#: ../../library/enum.rst:902 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:904 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:907 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:909 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:914 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:917 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:920 +msgid "" +":meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing " +"member." +msgstr "" + +#: ../../library/enum.rst:922 +msgid "" +":meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an " +"existing member." +msgstr "" + +#: ../../library/enum.rst:925 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:928 msgid "" "``_repr_*`` (e.g. ``_repr_html_``), as used in `IPython's rich display`_" msgstr "" -#: ../../library/enum.rst:871 +#: ../../library/enum.rst:930 msgid "``_missing_``, ``_order_``, ``_generate_next_value_``" msgstr "``_missing_``, ``_order_``, ``_generate_next_value_``" -#: ../../library/enum.rst:872 +#: ../../library/enum.rst:931 msgid "``_ignore_``" msgstr "``_ignore_``" -#: ../../library/enum.rst:873 +#: ../../library/enum.rst:932 msgid "``_add_alias_``, ``_add_value_alias_``, ``_repr_*``" msgstr "" -#: ../../library/enum.rst:879 +#: ../../library/enum.rst:938 msgid "Utilities and Decorators" msgstr "" -#: ../../library/enum.rst:883 +#: ../../library/enum.rst:942 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 +1524,54 @@ msgid "" "name. Care must be taken if mixing *auto()* with manually specified values." msgstr "" -#: ../../library/enum.rst:891 +#: ../../library/enum.rst:950 msgid "" "*auto* instances are only resolved when at the top level of an assignment:" msgstr "" -#: ../../library/enum.rst:893 +#: ../../library/enum.rst:952 msgid "``FIRST = auto()`` will work (auto() is replaced with ``1``);" msgstr "" -#: ../../library/enum.rst:894 +#: ../../library/enum.rst:953 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:955 msgid "" "``THREE = [auto(), -3]`` will *not* work (``, -3`` is used to " "create the ``THREE`` enum member)" msgstr "" -#: ../../library/enum.rst:901 +#: ../../library/enum.rst:960 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:963 msgid "" "``_generate_next_value_`` can be overridden to customize the values used by " "*auto*." msgstr "" -#: ../../library/enum.rst:907 +#: ../../library/enum.rst:966 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:972 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:976 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 +1579,55 @@ msgid "" "``name``." msgstr "" -#: ../../library/enum.rst:926 +#: ../../library/enum.rst:985 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:989 +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 "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Errado(Enum):\n" +"... UM = 1\n" +"... DOIS = 2\n" +"... TRES = 3\n" +"... QUATRO = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : QUATRO -> TRES" + +#: ../../library/enum.rst:1003 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:1011 msgid "A decorator for use in enums: its target will become a member." msgstr "" -#: ../../library/enum.rst:958 +#: ../../library/enum.rst:1017 msgid "A decorator for use in enums: its target will not become a member." msgstr "" -#: ../../library/enum.rst:964 +#: ../../library/enum.rst:1023 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 +1635,54 @@ msgid "" "namespace (see :class:`re.RegexFlag` for an example)." msgstr "" -#: ../../library/enum.rst:974 +#: ../../library/enum.rst:1032 msgid "Return a list of all power-of-two integers contained in a flag *value*." msgstr "" -#: ../../library/enum.rst:981 +#: ../../library/enum.rst:1040 msgid "Notes" msgstr "Notas" -#: ../../library/enum.rst:983 +#: ../../library/enum.rst:1042 msgid ":class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`" msgstr "" -#: ../../library/enum.rst:985 +#: ../../library/enum.rst:1044 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:1047 msgid "``__str__`` uses the value and not the name of the enum member" msgstr "" -#: ../../library/enum.rst:990 +#: ../../library/enum.rst:1049 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:1052 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:1055 +msgid "" +">>> from enum import Enum\n" +">>> class MyIntEnum(int, Enum):\n" +"... pass" +msgstr "" + +#: ../../library/enum.rst:1059 msgid "or you can reassign the appropriate :meth:`str`, etc., in your enum::" msgstr "" + +#: ../../library/enum.rst:1061 +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..26163eaa5 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..0b5e4618c 100644 --- a/library/exceptions.po +++ b/library/exceptions.po @@ -1,32 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-27 15:03+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +123,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 +264,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 ` " @@ -353,36 +365,40 @@ msgstr "" #: ../../library/exceptions.rst:207 msgid "" -"The :attr:`name` and :attr:`obj` attributes can be set using keyword-only " -"arguments to the constructor. When set they represent the name of the " -"attribute that was attempted to be accessed and the object that was accessed " -"for said attribute, respectively." +"The optional *name* and *obj* keyword-only arguments set the corresponding " +"attributes:" msgstr "" -"Os atributos :attr:`name` e :attr:`obj` podem ser configurados usando " -"argumentos somente-nomeados para o construtor. Quando configurados, eles " -"representam o nome do atributo que se tentou acessar e do objeto que foi " -"acessado por esse atributo, respectivamente." +"O argumentos somente-nomeados opcionais *name* e o *obj* definem o atributos " +"correspondente:" #: ../../library/exceptions.rst:212 +msgid "The name of the attribute that was attempted to be accessed." +msgstr "O nome do atributo que tentou-se fazer o acesso." + +#: ../../library/exceptions.rst:216 +msgid "The object that was accessed for the named attribute." +msgstr "O objeto que foi acessado para o atributo nomeado." + +#: ../../library/exceptions.rst:218 msgid "Added the :attr:`name` and :attr:`obj` attributes." msgstr "Adicionado os atributos :attr:`name` e :attr:`obj`." -#: ../../library/exceptions.rst:217 +#: ../../library/exceptions.rst:223 msgid "" "Raised when the :func:`input` function hits an end-of-file condition (EOF) " -"without reading any data. (N.B.: the :meth:`io.IOBase.read` and :meth:`io." +"without reading any data. (Note: the :meth:`!io.IOBase.read` and :meth:`io." "IOBase.readline` methods return an empty string when they hit EOF.)" msgstr "" "Levantado quando a função :func:`input` atinge uma condição de fim de " -"arquivo (EOF) sem ler nenhum dado. (Note: os métodos :meth:`io.IOBase.read` " +"arquivo (EOF) sem ler nenhum dado. (Note: os métodos :meth:`!io.IOBase.read` " "e :meth:`io.IOBase.readline` retornam uma string vazia quando pressionam o " "EOF.)" -#: ../../library/exceptions.rst:224 +#: ../../library/exceptions.rst:230 msgid "Not currently used." msgstr "Não usado atualmente." -#: ../../library/exceptions.rst:229 +#: ../../library/exceptions.rst:235 msgid "" "Raised when a :term:`generator` or :term:`coroutine` is closed; see :meth:" "`generator.close` and :meth:`coroutine.close`. It directly inherits from :" @@ -394,7 +410,7 @@ msgstr "" "diretamente de :exc:`BaseException` em vez de :exc:`Exception`, já que " "tecnicamente não é um erro." -#: ../../library/exceptions.rst:237 +#: ../../library/exceptions.rst:243 msgid "" "Raised when the :keyword:`import` statement has troubles trying to load a " "module. Also raised when the \"from list\" in ``from ... import`` has a " @@ -404,7 +420,7 @@ msgstr "" "carregar um módulo. Também é gerado quando o \"from list\" em ``from ... " "import`` tem um nome que não pode ser encontrado." -#: ../../library/exceptions.rst:241 +#: ../../library/exceptions.rst:247 msgid "" "The optional *name* and *path* keyword-only arguments set the corresponding " "attributes:" @@ -412,19 +428,19 @@ msgstr "" "O argumentos somente-nomeados opcionais *name* e o *path* definem o " "atributos correspondente:" -#: ../../library/exceptions.rst:246 +#: ../../library/exceptions.rst:252 msgid "The name of the module that was attempted to be imported." msgstr "O nome do módulo que tentou-se fazer a importação." -#: ../../library/exceptions.rst:250 +#: ../../library/exceptions.rst:256 msgid "The path to any file which triggered the exception." msgstr "O caminho para qualquer arquivo que acionou a exceção." -#: ../../library/exceptions.rst:252 +#: ../../library/exceptions.rst:258 msgid "Added the :attr:`name` and :attr:`path` attributes." msgstr "Adicionados os atributos :attr:`name` e :attr:`path`." -#: ../../library/exceptions.rst:257 +#: ../../library/exceptions.rst:263 msgid "" "A subclass of :exc:`ImportError` which is raised by :keyword:`import` when a " "module could not be located. It is also raised when ``None`` is found in :" @@ -434,7 +450,7 @@ msgstr "" "quando um módulo não pôde ser localizado. Também é levantada quando ``None`` " "é encontrado em :data:`sys.modules`." -#: ../../library/exceptions.rst:266 +#: ../../library/exceptions.rst:272 msgid "" "Raised when a sequence subscript is out of range. (Slice indices are " "silently truncated to fall in the allowed range; if an index is not an " @@ -444,7 +460,7 @@ msgstr "" "(Índices de fatia são truncados silenciosamente para cair num intervalo " "permitido; se um índice não for um inteiro, :exc:`TypeError` é levantada.)" -#: ../../library/exceptions.rst:275 +#: ../../library/exceptions.rst:281 msgid "" "Raised when a mapping (dictionary) key is not found in the set of existing " "keys." @@ -452,7 +468,7 @@ msgstr "" "Levantada quando uma chave de mapeamento (dicionário) não é encontrada no " "conjunto de chaves existentes." -#: ../../library/exceptions.rst:282 +#: ../../library/exceptions.rst:288 msgid "" "Raised when the user hits the interrupt key (normally :kbd:`Control-C` or :" "kbd:`Delete`). During execution, a check for interrupts is made regularly. " @@ -466,7 +482,7 @@ msgstr "" "para que não seja capturada acidentalmente por códigos que tratam :exc:" "`Exception` e assim evita que o interpretador saia." -#: ../../library/exceptions.rst:290 +#: ../../library/exceptions.rst:296 msgid "" "Catching a :exc:`KeyboardInterrupt` requires special consideration. Because " "it can be raised at unpredictable points, it may, in some circumstances, " @@ -481,7 +497,7 @@ msgstr "" "rápido possível ou evitar levantá-la de todo. (Veja :ref:`handlers-and-" "exceptions`.)" -#: ../../library/exceptions.rst:300 +#: ../../library/exceptions.rst:306 msgid "" "Raised when an operation runs out of memory but the situation may still be " "rescued (by deleting some objects). The associated value is a string " @@ -499,7 +515,7 @@ msgstr "" "completamente da situação; no entanto, levanta uma exceção para que um " "traceback possa ser impresso, no caso de um outro programa ser a causa." -#: ../../library/exceptions.rst:311 +#: ../../library/exceptions.rst:317 msgid "" "Raised when a local or global name is not found. This applies only to " "unqualified names. The associated value is an error message that includes " @@ -509,21 +525,19 @@ msgstr "" "apenas a nomes não qualificados. O valor associado é uma mensagem de erro " "que inclui o nome que não pode ser encontrado." -#: ../../library/exceptions.rst:315 -msgid "" -"The :attr:`name` attribute can be set using a keyword-only argument to the " -"constructor. When set it represent the name of the variable that was " -"attempted to be accessed." -msgstr "" -"O atributo :attr:`name` pode ser definido usando um argumento somente-" -"nomeado para o construtor. Quando definido, representa o nome da variável " -"que foi tentada ser acessada." +#: ../../library/exceptions.rst:321 +msgid "The optional *name* keyword-only argument sets the attribute:" +msgstr "O argumento somente-nomeado opcional *name* define o atributo:" -#: ../../library/exceptions.rst:319 +#: ../../library/exceptions.rst:325 +msgid "The name of the variable that was attempted to be accessed." +msgstr "O nome do variável que tentou-se fazer o acesso." + +#: ../../library/exceptions.rst:327 msgid "Added the :attr:`name` attribute." msgstr "Adicionado o atributo :attr:`name`." -#: ../../library/exceptions.rst:325 +#: ../../library/exceptions.rst:333 msgid "" "This exception is derived from :exc:`RuntimeError`. In user defined base " "classes, abstract methods should raise this exception when they require " @@ -536,7 +550,7 @@ msgstr "" "desenvolvida, para indicar que a implementação real ainda precisa ser " "adicionada." -#: ../../library/exceptions.rst:332 +#: ../../library/exceptions.rst:340 msgid "" "It should not be used to indicate that an operator or method is not meant to " "be supported at all -- in that case either leave the operator / method " @@ -546,17 +560,18 @@ msgstr "" "suportado -- nesse caso deixe o operador / método indefinido ou, se é uma " "subclasse, defina-o como :data:`None`." -#: ../../library/exceptions.rst:338 +#: ../../library/exceptions.rst:346 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:357 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 +582,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:361 msgid "" "The second form of the constructor sets the corresponding attributes, " "described below. The attributes default to :const:`None` if not specified. " @@ -581,7 +596,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:367 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 +610,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:375 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:379 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 +624,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:383 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,17 +636,17 @@ 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:391 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:" -"`FormatMessage` under Windows." +"formatted by the C functions :c:func:`!perror` under POSIX, and :c:func:`!" +"FormatMessage` under Windows." msgstr "" "A mensagem de erro correspondente, conforme fornecida pelo sistema " -"operacional. É formatada pelas funções C :c:func:`perror` no POSIX e :c:func:" -"`FormatMessage` no Windows." +"operacional. É formatada pelas funções C :c:func:`!perror` no POSIX e :c:" +"func:`!FormatMessage` no Windows." -#: ../../library/exceptions.rst:389 +#: ../../library/exceptions.rst:399 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,17 +660,17 @@ 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:406 msgid "" ":exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`, :exc:`socket." -"error`, :exc:`select.error` and :exc:`mmap.error` have been merged into :exc:" -"`OSError`, and the constructor may return a subclass." +"error`, :exc:`select.error` and :exc:`!mmap.error` have been merged into :" +"exc:`OSError`, and the constructor may return a subclass." msgstr "" ":exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`, :exc:`socket." -"error`, :exc:`select.error` e :exc:`mmap.error` foram fundidos em :exc:" +"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:412 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 +682,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:421 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 +699,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:431 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 +709,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:435 msgid "" "Examples of operations which can be blocked with a :exc:" "`PythonFinalizationError` during the Python finalization:" @@ -702,23 +717,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:438 msgid "Creating a new Python thread." msgstr "Criação de uma nova thread no Python." -#: ../../library/exceptions.rst:429 +#: ../../library/exceptions.rst:439 msgid ":func:`os.fork`." msgstr ":func:`os.fork`." -#: ../../library/exceptions.rst:431 +#: ../../library/exceptions.rst:441 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:443 ../../library/exceptions.rst:453 msgid "Previously, a plain :exc:`RuntimeError` was raised." msgstr "Anteriormente, uma :exc:`RuntimeError` simples era levantada." -#: ../../library/exceptions.rst:439 +#: ../../library/exceptions.rst:449 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 +743,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:459 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 +755,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:467 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 +765,7 @@ msgstr "" "categorias. O valor associado é uma string indicando o que precisamente deu " "errado." -#: ../../library/exceptions.rst:464 +#: ../../library/exceptions.rst:474 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 +775,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:480 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 +784,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:484 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 +795,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:489 msgid "" "If a generator code directly or indirectly raises :exc:`StopIteration`, it " "is converted into a :exc:`RuntimeError` (retaining the :exc:`StopIteration` " @@ -790,7 +805,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:493 msgid "" "Added ``value`` attribute and the ability for generator functions to use it " "to return a value." @@ -798,7 +813,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:497 msgid "" "Introduced the RuntimeError transformation via ``from __future__ import " "generator_stop``, see :pep:`479`." @@ -806,7 +821,7 @@ msgstr "" "Introduzida a transformação RuntimeError via ``from __future__ import " "generator_stop``, consulte :pep:`479`." -#: ../../library/exceptions.rst:491 +#: ../../library/exceptions.rst:501 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 +830,7 @@ msgstr "" "`StopIteration` levantado em um gerador é transformado em uma :exc:" "`RuntimeError`." -#: ../../library/exceptions.rst:497 +#: ../../library/exceptions.rst:507 msgid "" "Must be raised by :meth:`~object.__anext__` method of an :term:`asynchronous " "iterator` object to stop the iteration." @@ -823,7 +838,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:514 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 +850,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:520 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 +859,11 @@ msgstr "" "erro. Detalhes é uma tupla cujos membros também estão disponíveis como " "atributos separados." -#: ../../library/exceptions.rst:515 +#: ../../library/exceptions.rst:525 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:529 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 +871,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:534 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 +879,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:539 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:543 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,15 +891,15 @@ 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:548 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." msgstr "" -"A coluna da linha final em que erro ocorrido finaliza Este é indexado em 1: " +"A coluna da linha final em que o erro ocorreu termina. Este é indexado em 1: " "o primeiro caractere na linha tem um ``offset`` de 1." -#: ../../library/exceptions.rst:541 +#: ../../library/exceptions.rst:551 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 +912,11 @@ msgstr "" "resulta neste atributo de argumentos: ('f-string: ...', ('', 1, 2, '(a " "b)\\n', 1, 5))." -#: ../../library/exceptions.rst:546 +#: ../../library/exceptions.rst:556 msgid "Added the :attr:`end_lineno` and :attr:`end_offset` attributes." -msgstr "Adicionado os atributos :attr:`end_lineno` e :attr:`end_offset`." +msgstr "Adicionados os atributos :attr:`end_lineno` e :attr:`end_offset`." -#: ../../library/exceptions.rst:551 +#: ../../library/exceptions.rst:561 msgid "" "Base class for syntax errors related to incorrect indentation. This is a " "subclass of :exc:`SyntaxError`." @@ -909,7 +924,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:567 msgid "" "Raised when indentation contains an inconsistent use of tabs and spaces. " "This is a subclass of :exc:`IndentationError`." @@ -917,32 +932,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:573 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:579 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:590 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 " @@ -951,7 +972,7 @@ msgid "" "it is not handled, the Python interpreter exits; no stack traceback is " "printed. The constructor accepts the same optional argument passed to :func:" "`sys.exit`. If the value is an integer, it specifies the system exit status " -"(passed to C's :c:func:`exit` function); if it is ``None``, the exit status " +"(passed to C's :c:func:`!exit` function); if it is ``None``, the exit status " "is zero; if it has another type (such as a string), the object's value is " "printed and the exit status is one." msgstr "" @@ -962,11 +983,11 @@ msgstr "" "não é tratado, o interpretador Python sai; nenhum traceback (situação da " "pilha de execução) é impresso. O construtor aceita o mesmo argumento " "opcional passado para :func:`sys.exit`. Se o valor for um inteiro, ele " -"especifica o status de saída do sistema (passado para a função C :c:func:" -"`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." +"especifica o status de saída do sistema (passado para a função C :c:func:`!" +"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:601 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 +1003,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:610 msgid "" "The exit status or error message that is passed to the constructor. " "(Defaults to ``None``.)" @@ -990,7 +1011,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:616 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 +1021,7 @@ msgstr "" "inadequado. O valor associado é uma string que fornece detalhes sobre a " "incompatibilidade de tipo." -#: ../../library/exceptions.rst:605 +#: ../../library/exceptions.rst:619 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 +1034,7 @@ msgstr "" "implementação, :exc:`NotImplementedError` é a exceção apropriada a ser " "levantada." -#: ../../library/exceptions.rst:610 +#: ../../library/exceptions.rst:624 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 +1046,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:631 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 +1056,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:638 msgid "" "Raised when a Unicode-related encoding or decoding error occurs. It is a " "subclass of :exc:`ValueError`." @@ -1043,7 +1064,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:641 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 +1074,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:647 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:651 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:655 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:659 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:663 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:668 msgid "" "Raised when a Unicode-related error occurs during encoding. It is a " "subclass of :exc:`UnicodeError`." @@ -1081,7 +1102,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:674 msgid "" "Raised when a Unicode-related error occurs during decoding. It is a " "subclass of :exc:`UnicodeError`." @@ -1089,7 +1110,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:680 msgid "" "Raised when a Unicode-related error occurs during translating. It is a " "subclass of :exc:`UnicodeError`." @@ -1097,7 +1118,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:686 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 +1128,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:693 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 +1138,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:698 msgid "" "The following exceptions are kept for compatibility with previous versions; " "starting from Python 3.3, they are aliases of :exc:`OSError`." @@ -1125,15 +1146,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:707 msgid "Only available on Windows." msgstr "Disponível apenas no Windows." -#: ../../library/exceptions.rst:697 +#: ../../library/exceptions.rst:711 msgid "OS exceptions" msgstr "Exceções de sistema operacional" -#: ../../library/exceptions.rst:699 +#: ../../library/exceptions.rst:713 msgid "" "The following exceptions are subclasses of :exc:`OSError`, they get raised " "depending on the system error code." @@ -1141,7 +1162,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:718 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 +1174,7 @@ msgstr "" "`~errno.EAGAIN`, :py:const:`~errno.EALREADY`, :py:const:`~errno.EWOULDBLOCK` " "e :py:const:`~errno.EINPROGRESS`." -#: ../../library/exceptions.rst:709 +#: ../../library/exceptions.rst:723 msgid "" "In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have one " "more attribute:" @@ -1161,7 +1182,7 @@ msgstr "" "Além daquelas de :exc:`OSError`, :exc:`BlockingIOError` pode ter mais um " "atributo:" -#: ../../library/exceptions.rst:714 +#: ../../library/exceptions.rst:728 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 +1192,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:734 msgid "" "Raised when an operation on a child process failed. Corresponds to :c:data:" "`errno` :py:const:`~errno.ECHILD`." @@ -1179,11 +1200,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:739 msgid "A base class for connection-related issues." msgstr "Uma classe base para problemas relacionados à conexão." -#: ../../library/exceptions.rst:727 +#: ../../library/exceptions.rst:741 msgid "" "Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, :exc:" "`ConnectionRefusedError` and :exc:`ConnectionResetError`." @@ -1191,7 +1212,7 @@ msgstr "" "Suas subclasses são :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, :" "exc:`ConnectionRefusedError` e :exc:`ConnectionResetError`." -#: ../../library/exceptions.rst:732 +#: ../../library/exceptions.rst:746 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 +1224,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:753 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 +1234,7 @@ msgstr "" "conexão é cancelada pelo par. Corresponde a :c:data:`errno` :py:const:" "`~errno.ECONNABORTED`." -#: ../../library/exceptions.rst:745 +#: ../../library/exceptions.rst:759 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 +1244,7 @@ msgstr "" "conexão é recusada pelo par. Corresponde a :c:data:`errno` :py:const:`~errno." "ECONNREFUSED`." -#: ../../library/exceptions.rst:751 +#: ../../library/exceptions.rst:765 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 +1253,7 @@ msgstr "" "redefinida pelo par. Corresponde a :c:data:`errno` :py:const:`~errno." "ECONNRESET`." -#: ../../library/exceptions.rst:757 +#: ../../library/exceptions.rst:771 msgid "" "Raised when trying to create a file or directory which already exists. " "Corresponds to :c:data:`errno` :py:const:`~errno.EEXIST`." @@ -1240,7 +1261,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:776 msgid "" "Raised when a file or directory is requested but doesn't exist. Corresponds " "to :c:data:`errno` :py:const:`~errno.ENOENT`." @@ -1248,7 +1269,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:781 msgid "" "Raised when a system call is interrupted by an incoming signal. Corresponds " "to :c:data:`errno` :py:const:`~errno.EINTR`." @@ -1256,7 +1277,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:784 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 +1288,7 @@ msgstr "" "(veja :pep:`475` para a justificativa), em vez de levantar :exc:" "`InterruptedError`." -#: ../../library/exceptions.rst:777 +#: ../../library/exceptions.rst:791 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 +1297,7 @@ msgstr "" "solicitada em um diretório. Corresponde a :c:data:`errno` :py:const:`~errno." "EISDIR`." -#: ../../library/exceptions.rst:783 +#: ../../library/exceptions.rst:797 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 +1311,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:805 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 +1323,7 @@ msgstr "" "data:`errno` :py:const:`~errno.EACCES`, :py:const:`~errno.EPERM`, e :py:" "const:`~errno.ENOTCAPABLE`." -#: ../../library/exceptions.rst:796 +#: ../../library/exceptions.rst:810 msgid "" "WASI's :py:const:`~errno.ENOTCAPABLE` is now mapped to :exc:" "`PermissionError`." @@ -1310,7 +1331,7 @@ msgstr "" ":py:const:`~errno.ENOTCAPABLE` do WASI agora é mapeado para :exc:" "`PermissionError`." -#: ../../library/exceptions.rst:802 +#: ../../library/exceptions.rst:816 msgid "" "Raised when a given process doesn't exist. Corresponds to :c:data:`errno` :" "py:const:`~errno.ESRCH`." @@ -1318,7 +1339,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:821 msgid "" "Raised when a system function timed out at the system level. Corresponds to :" "c:data:`errno` :py:const:`~errno.ETIMEDOUT`." @@ -1326,19 +1347,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:824 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:830 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:836 msgid "Warnings" msgstr "Avisos" -#: ../../library/exceptions.rst:824 +#: ../../library/exceptions.rst:838 msgid "" "The following exceptions are used as warning categories; see the :ref:" "`warning-categories` documentation for more details." @@ -1346,15 +1367,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:843 msgid "Base class for warning categories." msgstr "Classe base para categorias de aviso." -#: ../../library/exceptions.rst:834 +#: ../../library/exceptions.rst:848 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:853 msgid "" "Base class for warnings about deprecated features when those warnings are " "intended for other Python developers." @@ -1362,7 +1383,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:856 msgid "" "Ignored by the default warning filters, except in the ``__main__`` module (:" "pep:`565`). Enabling the :ref:`Python Development Mode ` shows this " @@ -1372,11 +1393,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:860 ../../library/exceptions.rst:876 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:865 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 +1405,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:869 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 +1415,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:873 ../../library/exceptions.rst:902 +#: ../../library/exceptions.rst:929 msgid "" "Ignored by the default warning filters. Enabling the :ref:`Python " "Development Mode ` shows this warning." @@ -1403,16 +1424,24 @@ 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:881 msgid "Base class for warnings about dubious syntax." msgstr "Classe base para avisos sobre sintaxe duvidosa." -#: ../../library/exceptions.rst:872 +#: ../../library/exceptions.rst:883 +msgid "" +"This warning is typically emitted when compiling Python source code, and " +"usually won't be reported when running already compiled code." +msgstr "" +"Este aviso normalmente é emitido ao compilar código-fonte Python e " +"normalmente não será relatado ao executar código já compilado." + +#: ../../library/exceptions.rst:889 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:894 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 +1449,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:900 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:908 msgid "Base class for warnings related to Unicode." msgstr "Classe base para avisos relacionados a Unicode." -#: ../../library/exceptions.rst:896 +#: ../../library/exceptions.rst:913 msgid "Base class for warnings related to encodings." msgstr "Classe base para avisos relacionados a codificações." -#: ../../library/exceptions.rst:898 +#: ../../library/exceptions.rst:915 msgid "See :ref:`io-encoding-warning` for details." msgstr "Veja :ref:`io-encoding-warning` para detalhes." -#: ../../library/exceptions.rst:905 +#: ../../library/exceptions.rst:922 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:927 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:938 msgid "Exception groups" msgstr "Grupos de exceções" -#: ../../library/exceptions.rst:923 +#: ../../library/exceptions.rst:940 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 +1494,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:949 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 +1512,7 @@ msgstr "" "``except Exception`` capture um :exc:`ExceptionGroup` mas não :exc:" "`BaseExceptionGroup`." -#: ../../library/exceptions.rst:940 +#: ../../library/exceptions.rst:957 msgid "" "The :exc:`BaseExceptionGroup` constructor returns an :exc:`ExceptionGroup` " "rather than a :exc:`BaseExceptionGroup` if all contained exceptions are :exc:" @@ -1498,12 +1527,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:966 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:970 msgid "" "A tuple of the exceptions in the ``excs`` sequence given to the constructor. " "This is a read-only attribute." @@ -1511,7 +1540,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:975 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 +1549,7 @@ msgstr "" "que correspondem à condição *condition* ou ``None`` se o resultado estiver " "vazio." -#: ../../library/exceptions.rst:961 +#: ../../library/exceptions.rst:978 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 +1564,7 @@ msgstr "" "único argumento e retorna verdadeiro para a exceção que deve estar no " "subgrupo." -#: ../../library/exceptions.rst:967 +#: ../../library/exceptions.rst:984 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 +1578,7 @@ msgstr "" "__context__` e :attr:`~BaseException.__notes__`. Grupos aninhados vazios são " "omitidos do resultado." -#: ../../library/exceptions.rst:974 +#: ../../library/exceptions.rst:991 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 +1589,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:995 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:1000 msgid "" "Like :meth:`subgroup`, but returns the pair ``(match, rest)`` where " "``match`` is ``subgroup(condition)`` and ``rest`` is the remaining non-" @@ -1574,7 +1603,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:1006 msgid "" "Returns an exception group with the same :attr:`message`, but which wraps " "the exceptions in ``excs``." @@ -1582,7 +1611,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:1009 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 +1623,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:1015 msgid "" ":meth:`subgroup` and :meth:`split` copy the :attr:`~BaseException." "__traceback__`, :attr:`~BaseException.__cause__`, :attr:`~BaseException." @@ -1608,12 +1637,66 @@ 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:1022 +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:1048 msgid "" "Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so " "subclasses that need a different constructor signature need to override that " "rather than :meth:`~object.__init__`. For example, the following defines an " -"exception group subclass which accepts an exit_code and and constructs the " +"exception group subclass which accepts an exit_code and constructs the " "group's message from it. ::" msgstr "" "Observe que :exc:`BaseExceptionGroup` define :meth:`~object.__new__`, então " @@ -1622,7 +1705,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:1054 +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:1063 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 +1735,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:1071 msgid "Exception hierarchy" msgstr "Hierarquia das exceções" -#: ../../library/exceptions.rst:1056 +#: ../../library/exceptions.rst:1073 msgid "The class hierarchy for built-in exceptions is:" msgstr "A hierarquia de classes para exceções embutidas é:" +#: ../../library/exceptions.rst:1075 +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 +1924,10 @@ msgstr "__suppress_context__ (atributo de exceção)" msgid "assert" msgstr "assert" -#: ../../library/exceptions.rst:345 +#: ../../library/exceptions.rst:355 msgid "module" msgstr "módulo" -#: ../../library/exceptions.rst:345 +#: ../../library/exceptions.rst:355 msgid "errno" msgstr "errno" diff --git a/library/faulthandler.po b/library/faulthandler.po index dff6c2206..b12dfa88f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..a2a4ad263 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..cffb246c6 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..416ed8b8f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..a18837d2f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..2e8ef0c96 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..c1b9f9fc1 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..e7d9e892f 100644 --- a/library/fractions.po +++ b/library/fractions.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-25 15:05+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,18 +41,18 @@ msgstr "" #: ../../library/fractions.rst:17 msgid "" -"A Fraction instance can be constructed from a pair of integers, from another " -"rational number, or from a string." +"A Fraction instance can be constructed from a pair of rational numbers, from " +"a single number, or from a string." msgstr "" "Uma instância de Fraction pode ser construída a partir de um par de números " -"inteiros, de outro número racional ou de uma string." +"racionais, de um único número ou de uma string." #: ../../library/fractions.rst:26 msgid "" "The first version requires that *numerator* and *denominator* are instances " "of :class:`numbers.Rational` and returns a new :class:`Fraction` instance " -"with value ``numerator/denominator``. If *denominator* is ``0``, it raises " -"a :exc:`ZeroDivisionError`. The second version requires that " +"with a value equal to ``numerator/denominator``. If *denominator* is zero, " +"it raises a :exc:`ZeroDivisionError`. The second version requires that " "*other_fraction* is an instance of :class:`numbers.Rational` and returns a :" "class:`Fraction` instance with the same value. The next two versions accept " "either a :class:`float` or a :class:`decimal.Decimal` instance, and return " @@ -65,18 +66,23 @@ msgid "" msgstr "" "A primeira versão requer que *numerator* e *denominator* sejam instâncias " "de :class:`numbers.Rational` e retorna uma nova instância de :class:" -"`Fraction` com o valor ``numerator/denominator``. Se *denominator* for " -"``0``, ele levanta uma :exc:`ZeroDivisionError`. A segunda versão requer que " -"*other_fraction* seja uma instância de :class:`numbers.Rational` e retorna " -"uma instância de :class:`Fraction` com o mesmo valor. As próximas duas " -"versões aceitam uma instância de :class:`float` ou :class:`decimal.Decimal` " -"e retornam uma instância de :class:`Fraction` com exatamente o mesmo valor. " -"Note que devido aos problemas usuais com ponto flutuante binário (veja :ref:" -"`tut-fp-issues`), o argumento para ``Fraction(1.1)`` não é exatamente igual " -"a 11/10, e então ``Fraction(1.1)`` *não* retorna ``Fraction(11, 10)`` como " -"seria de se esperar. (Mas veja a documentação para o método :meth:" -"`limit_denominator` abaixo.) A última versão do construtor espera uma " -"instância de string ou unicode. A forma usual para esta instância é::" +"`Fraction` com um valor igual a ``numerator/denominator``. Se *denominator* " +"for zero, ele levanta uma :exc:`ZeroDivisionError`. A segunda versão requer " +"que *other_fraction* seja uma instância de :class:`numbers.Rational` e " +"retorna uma instância de :class:`Fraction` com o mesmo valor. As próximas " +"duas versões aceitam uma instância de :class:`float` ou :class:`decimal." +"Decimal` e retornam uma instância de :class:`Fraction` com exatamente o " +"mesmo valor. Note que devido aos problemas usuais com ponto flutuante " +"binário (veja :ref:`tut-fp-issues`), o argumento para ``Fraction(1.1)`` não " +"é exatamente igual a 11/10, e então ``Fraction(1.1)`` *não* retorna " +"``Fraction(11, 10)`` como seria de se esperar. (Mas veja a documentação para " +"o método :meth:`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 "" @@ -90,12 +96,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:" @@ -175,10 +233,10 @@ msgid "Numerator of the Fraction in lowest term." msgstr "Numerador de Fraction no menor termo." #: ../../library/fractions.rst:119 -msgid "Denominator of the Fraction in lowest term." -msgstr "Denominador de Fraction no menor termo." +msgid "Denominator of the Fraction in lowest terms. Guaranteed to be positive." +msgstr "Denominador de Fraction em termos mínimos. Garantidamente positivo." -#: ../../library/fractions.rst:124 +#: ../../library/fractions.rst:125 msgid "" "Return a tuple of two integers, whose ratio is equal to the original " "Fraction. The ratio is in lowest terms and has a positive denominator." @@ -186,11 +244,11 @@ msgstr "" "Retorna uma tupla de dois inteiros, cuja razão é igual a Fraction original. " "A razão está em termos mais baixos e tem um denominador positivo." -#: ../../library/fractions.rst:132 +#: ../../library/fractions.rst:133 msgid "Return ``True`` if the Fraction is an integer." msgstr "Retorna ``True`` se a Fraction for um inteiro." -#: ../../library/fractions.rst:138 +#: ../../library/fractions.rst:139 msgid "" "Alternative constructor which only accepts instances of :class:`float` or :" "class:`numbers.Integral`. Beware that ``Fraction.from_float(0.3)`` is not " @@ -200,7 +258,7 @@ msgstr "" "class:`numbers.Integral`. Esteja ciente de que ``Fraction.from_float(0.3)`` " "não é o mesmo valor que ``Fraction(3, 10)``." -#: ../../library/fractions.rst:144 +#: ../../library/fractions.rst:145 msgid "" "From Python 3.2 onwards, you can also construct a :class:`Fraction` instance " "directly from a :class:`float`." @@ -208,7 +266,7 @@ msgstr "" "A partir do Python 3.2, você também pode construir uma instância :class:" "`Fraction` diretamente de um :class:`float`." -#: ../../library/fractions.rst:150 +#: ../../library/fractions.rst:151 msgid "" "Alternative constructor which only accepts instances of :class:`decimal." "Decimal` or :class:`numbers.Integral`." @@ -216,7 +274,7 @@ msgstr "" "Construtor alternativo que aceita somente instâncias de :class:`decimal." "Decimal` ou :class:`numbers.Integral`." -#: ../../library/fractions.rst:155 +#: ../../library/fractions.rst:156 msgid "" "From Python 3.2 onwards, you can also construct a :class:`Fraction` instance " "directly from a :class:`decimal.Decimal` instance." @@ -224,7 +282,7 @@ msgstr "" "A partir do Python 3.2, você também pode construir uma instância :class:" "`Fraction` diretamente de uma instância de :class:`decimal.Decimal`." -#: ../../library/fractions.rst:162 +#: ../../library/fractions.rst:163 msgid "" "Finds and returns the closest :class:`Fraction` to ``self`` that has " "denominator at most max_denominator. This method is useful for finding " @@ -234,13 +292,13 @@ msgstr "" "denominador no máximo max_denominator. Este método é útil para encontrar " "aproximações racionais para um dado número de ponto flutuante:" -#: ../../library/fractions.rst:170 +#: ../../library/fractions.rst:171 msgid "or for recovering a rational number that's represented as a float:" msgstr "" "ou para recuperar um número racional que é representado como um ponto " "flutuante:" -#: ../../library/fractions.rst:183 +#: ../../library/fractions.rst:184 msgid "" "Returns the greatest :class:`int` ``<= self``. This method can also be " "accessed through the :func:`math.floor` function:" @@ -248,7 +306,7 @@ msgstr "" "Retorna o maior :class:`int` ``<= self``. Este método também pode ser " "acessado por meio da função :func:`math.floor`:" -#: ../../library/fractions.rst:193 +#: ../../library/fractions.rst:194 msgid "" "Returns the least :class:`int` ``>= self``. This method can also be " "accessed through the :func:`math.ceil` function." @@ -256,7 +314,7 @@ msgstr "" "Retorna o menor :class:`int` ``>= self``. Este método também pode ser " "acessado por meio da função :func:`math.ceil`." -#: ../../library/fractions.rst:200 +#: ../../library/fractions.rst:201 msgid "" "The first version returns the nearest :class:`int` to ``self``, rounding " "half to even. The second version rounds ``self`` to the nearest multiple of " @@ -270,7 +328,7 @@ msgstr "" "``ndigits`` for negativo), novamente arredondando a metade para par. Este " "método também pode ser acessado por meio da função :func:`round`." -#: ../../library/fractions.rst:208 +#: ../../library/fractions.rst:209 msgid "" "Provides support for formatting of :class:`Fraction` instances via the :meth:" "`str.format` method, the :func:`format` built-in function, or :ref:" @@ -280,7 +338,7 @@ msgstr "" "do método :meth:`str.format`, da função embutida :func:`format` ou :ref:" "`literais de strings formatadas `." -#: ../../library/fractions.rst:212 +#: ../../library/fractions.rst:213 msgid "" "If the ``format_spec`` format specification string does not end with one of " "the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``, ``'G'`` " @@ -302,7 +360,7 @@ msgstr "" "inteiro exato. O sinalizador de preenchimento de zeros ``'0'`` não é " "suportado." -#: ../../library/fractions.rst:222 +#: ../../library/fractions.rst:223 msgid "" "If the ``format_spec`` format specification string ends with one of the " "presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``, ``'G'`` or " @@ -314,14 +372,54 @@ msgstr "" "ou ``'%'``, então a formatação segue as regras descritas para o tipo :class:" "`float` na seção :ref:`formatspec`." -#: ../../library/fractions.rst:227 +#: ../../library/fractions.rst:228 msgid "Here are some examples::" msgstr "Veja alguns exemplos::" -#: ../../library/fractions.rst:251 +#: ../../library/fractions.rst:230 +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:252 msgid "Module :mod:`numbers`" msgstr "Módulo :mod:`numbers`" -#: ../../library/fractions.rst:252 +#: ../../library/fractions.rst:253 msgid "The abstract base classes making up the numeric tower." msgstr "As classes base abstratas que compõem a torre numérica." diff --git a/library/frameworks.po b/library/frameworks.po index d4d7ce813..21495266a 100644 --- a/library/frameworks.po +++ b/library/frameworks.po @@ -1,44 +1,50 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/frameworks.rst:5 -msgid "Program Frameworks" +#: ../../library/frameworks.rst:7 +msgid "Program frameworks" msgstr "Frameworks de programa" -#: ../../library/frameworks.rst:7 +#: ../../library/frameworks.rst:9 msgid "" -"The modules described in this chapter are frameworks that will largely " -"dictate the structure of your program. Currently the modules described " -"here are all oriented toward writing command-line interfaces." +"This chapter is no longer maintained, and the modules it contained have been " +"moved to their respective topical documentation." msgstr "" -"Os módulos descritos neste capítulo são frameworks que ditarão em grande " -"parte a estrutura do seu programa. Atualmente, os módulos descritos aqui são " -"todos orientados para escrever interfaces de linha de comando." +"Este capítulo não é mais mantido, e os módulos que ele continha foram " +"movidos para suas respectivas documentações temáticas." #: ../../library/frameworks.rst:11 -msgid "The full list of modules described in this chapter is:" -msgstr "A lista completa de módulos descritos neste capítulo é:" +msgid ":mod:`cmd` — :doc:`Command Line Interface Libraries <./cmdlinelibs>`" +msgstr "" +":mod:`cmd` — :doc:`Bibliotecas de interface de linha de comando <./" +"cmdlinelibs>`" + +#: ../../library/frameworks.rst:12 +msgid ":mod:`shlex` — :doc:`Unix Specific Services <./unix>`" +msgstr ":mod:`shlex` — :doc:`Serviços específicos do Unix <./unix>`" + +#: ../../library/frameworks.rst:13 +msgid ":mod:`turtle` — :doc:`Graphical User Interfaces with Tk <./tk>`" +msgstr ":mod:`turtle` — :doc:`Interfaces gráficas de usuário com Tk <./tk>`" diff --git a/library/ftplib.po b/library/ftplib.po index 0e7129bc4..42a862703 100644 --- a/library/ftplib.po +++ b/library/ftplib.po @@ -1,27 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 @@ 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 +62,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" @@ -488,15 +509,35 @@ msgid "" "The class now supports hostname check with :attr:`ssl.SSLContext." "check_hostname` and *Server Name Indication* (see :const:`ssl.HAS_SNI`)." msgstr "" +"A classe agora oferece suporte a verificação de nome de host com :attr:`ssl." +"SSLContext.check_hostname` e *Indicação de nome de servidor* (veja :const:" +"`ssl.HAS_SNI`)." #: ../../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..a8a1e1cab 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..a4c91858c 100644 --- a/library/functions.po +++ b/library/functions.po @@ -1,39 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-11-11 15:06+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +433,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 +483,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 " @@ -497,14 +512,14 @@ msgstr "" #: ../../library/functions.rst:124 msgid "" "Convert an integer number to a binary string prefixed with \"0b\". The " -"result is a valid Python expression. If *x* is not a Python :class:`int` " -"object, it has to define an :meth:`~object.__index__` method that returns an " -"integer. Some examples:" +"result is a valid Python expression. If *integer* is not a Python :class:" +"`int` object, it has to define an :meth:`~object.__index__` method that " +"returns an integer. Some examples:" msgstr "" "Converte um número inteiro para uma string de binários prefixada com \"0b\". " -"O resultado é uma expressão Python válida. Se *x* não é um objeto Python :" -"class:`int`, ele tem que definir um método :meth:`~object.__index__` que " -"devolve um inteiro. Alguns exemplos:" +"O resultado é uma expressão Python válida. Se *integer* não é um objeto " +"Python :class:`int`, ele tem que definir um método :meth:`~object.__index__` " +"que devolve um inteiro. Alguns exemplos:" #: ../../library/functions.rst:134 msgid "" @@ -514,8 +529,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:940 +#: ../../library/functions.rst:1321 msgid "See also :func:`format` for more information." msgstr "Veja também :func:`format` para mais informações." @@ -535,7 +550,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:805 msgid "The parameter is now positional-only." msgstr "O parâmetro agora é somente-posicional" @@ -543,7 +558,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 +569,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 " @@ -588,7 +603,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``builtins.breakpoint`` com " "o argumento ``breakpointhook``." -#: ../../library/functions.rst:190 +#: ../../library/functions.rst:189 msgid "" "Return a new array of bytes. The :class:`bytearray` class is a mutable " "sequence of integers in the range 0 <= x < 256. It has most of the usual " @@ -601,7 +616,7 @@ msgstr "" "mutable`, assim como a maior parte dos métodos que o tipo :class:`bytes` " "tem, veja :ref:`bytes-methods`." -#: ../../library/functions.rst:195 +#: ../../library/functions.rst:194 msgid "" "The optional *source* parameter can be used to initialize the array in a few " "different ways:" @@ -609,7 +624,7 @@ msgstr "" "O parâmetro opcional *source* pode ser usado para inicializar o vetor de " "algumas maneiras diferentes:" -#: ../../library/functions.rst:198 +#: ../../library/functions.rst:197 msgid "" "If it is a *string*, you must also give the *encoding* (and optionally, " "*errors*) parameters; :func:`bytearray` then converts the string to bytes " @@ -619,7 +634,7 @@ msgstr "" "opcionalmente, *errors*); :func:`bytearray` então converte a string para " "bytes usando :meth:`str.encode`." -#: ../../library/functions.rst:202 +#: ../../library/functions.rst:201 msgid "" "If it is an *integer*, the array will have that size and will be initialized " "with null bytes." @@ -627,7 +642,7 @@ msgstr "" "Se é um *inteiro*, o vetor terá esse tamanho e será inicializado com bytes " "nulos." -#: ../../library/functions.rst:205 +#: ../../library/functions.rst:204 msgid "" "If it is an object conforming to the :ref:`buffer interface " "`, a read-only buffer of the object will be used to " @@ -637,7 +652,7 @@ msgstr "" "`, um buffer somente leitura do objeto será usado para " "inicializar o vetor de bytes." -#: ../../library/functions.rst:208 +#: ../../library/functions.rst:207 msgid "" "If it is an *iterable*, it must be an iterable of integers in the range ``0 " "<= x < 256``, which are used as the initial contents of the array." @@ -645,15 +660,15 @@ msgstr "" "Se é um *iterável*, deve ser um iterável de inteiros no intervalo ``0 <= x < " "256``, que serão usados como o conteúdo inicial do vetor." -#: ../../library/functions.rst:211 +#: ../../library/functions.rst:210 msgid "Without an argument, an array of size 0 is created." msgstr "Sem nenhum argumento, um vetor de tamanho 0 é criado." -#: ../../library/functions.rst:213 +#: ../../library/functions.rst:212 msgid "See also :ref:`binaryseq` and :ref:`typebytearray`." msgstr "Veja também :ref:`binaryseq` e :ref:`typebytearray`." -#: ../../library/functions.rst:222 +#: ../../library/functions.rst:220 msgid "" "Return a new \"bytes\" object which is an immutable sequence of integers in " "the range ``0 <= x < 256``. :class:`bytes` is an immutable version of :" @@ -665,24 +680,24 @@ msgstr "" "`bytearray` -- tem os mesmos métodos de objetos imutáveis e o mesmo " "comportamento de índices e fatiamento." -#: ../../library/functions.rst:227 +#: ../../library/functions.rst:225 msgid "" "Accordingly, constructor arguments are interpreted as for :func:`bytearray`." msgstr "" "Consequentemente, argumentos do construtor são interpretados como os de :" "func:`bytearray`." -#: ../../library/functions.rst:229 +#: ../../library/functions.rst:227 msgid "Bytes objects can also be created with literals, see :ref:`strings`." msgstr "" "Objetos bytes também podem ser criados com literais, veja :ref:`strings`." -#: ../../library/functions.rst:231 +#: ../../library/functions.rst:229 msgid "See also :ref:`binaryseq`, :ref:`typebytes`, and :ref:`bytes-methods`." msgstr "" "Veja também :ref:`binaryseq`, :ref:`typebytes`, e :ref:`bytes-methods`." -#: ../../library/functions.rst:236 +#: ../../library/functions.rst:234 msgid "" "Return :const:`True` if the *object* argument appears callable, :const:" "`False` if not. If this returns ``True``, it is still possible that a call " @@ -697,36 +712,36 @@ msgstr "" "instâncias são chamáveis se suas classes possuem um método :meth:`~object." "__call__`." -#: ../../library/functions.rst:242 +#: ../../library/functions.rst:240 msgid "" "This function was first removed in Python 3.0 and then brought back in " "Python 3.2." msgstr "Esta função foi removida na versão 3.0, mas retornou no Python 3.2." -#: ../../library/functions.rst:249 +#: ../../library/functions.rst:247 msgid "" -"Return the string representing a character whose Unicode code point is the " -"integer *i*. For example, ``chr(97)`` returns the string ``'a'``, while " +"Return the string representing a character with the specified Unicode code " +"point. For example, ``chr(97)`` returns the string ``'a'``, while " "``chr(8364)`` returns the string ``'€'``. This is the inverse of :func:`ord`." msgstr "" -"Retorna o caractere que é apontado pelo inteiro *i* no código Unicode. Por " -"exemplo, ``chr(97)`` retorna a string ``'a'``, enquanto ``chr(8364)`` " -"retorna a string ``'€'``. É o inverso de :func:`ord`." +"Retorna a string representando um caractere com o ponto de código Unicode " +"especificado. Por exemplo, ``chr(97)`` retorna a string ``'a'``, enquanto " +"``chr(8364)`` retorna a string ``'€'``. É o inverso de :func:`ord`." -#: ../../library/functions.rst:253 +#: ../../library/functions.rst:251 msgid "" "The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in " -"base 16). :exc:`ValueError` will be raised if *i* is outside that range." +"base 16). :exc:`ValueError` will be raised if it is outside that range." msgstr "" "O intervalo válido para o argumento vai de 0 até 1.114.111 (0x10FFFF na base " -"16). Será lançada uma exceção :exc:`ValueError` se *i* estiver fora desse " +"16). Será lançada uma exceção :exc:`ValueError` se ele estiver fora desse " "intervalo." -#: ../../library/functions.rst:259 +#: ../../library/functions.rst:257 msgid "Transform a method into a class method." msgstr "Transforma um método em um método de classe." -#: ../../library/functions.rst:261 +#: ../../library/functions.rst:259 msgid "" "A class method receives the class as an implicit first argument, just like " "an instance method receives the instance. To declare a class method, use " @@ -736,7 +751,17 @@ 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:269 +#: ../../library/functions.rst:263 +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:267 msgid "" "The ``@classmethod`` form is a function :term:`decorator` -- see :ref:" "`function` for details." @@ -744,7 +769,7 @@ msgstr "" "O termo ``@classmethod`` é uma função :term:`decoradora ` -- " "veja :ref:`function` para detalhes." -#: ../../library/functions.rst:272 +#: ../../library/functions.rst:270 msgid "" "A class method can be called either on the class (such as ``C.f()``) or on " "an instance (such as ``C().f()``). The instance is ignored except for its " @@ -756,7 +781,7 @@ msgstr "" "por sua classe. Se um método de classe é chamado por uma classe derivada, o " "objeto da classe derivada é passado como primeiro argumento implícito." -#: ../../library/functions.rst:277 +#: ../../library/functions.rst:275 msgid "" "Class methods are different than C++ or Java static methods. If you want " "those, see :func:`staticmethod` in this section. For more information on " @@ -766,7 +791,7 @@ msgstr "" "você quer saber desses, veja :func:`staticmethod` nesta seção. Para mais " "informações sobre métodos de classe, consulte :ref:`types`." -#: ../../library/functions.rst:281 +#: ../../library/functions.rst:279 msgid "" "Class methods can now wrap other :term:`descriptors ` such as :" "func:`property`." @@ -774,15 +799,17 @@ msgstr "" "Métodos de classe agora podem envolver outros :term:`descritores " "` tal como :func:`property`." -#: ../../library/functions.rst:285 +#: ../../library/functions.rst:283 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 msgid "" @@ -967,11 +994,47 @@ 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:382 ../../library/functions.rst:750 +#: ../../library/functions.rst:996 msgid "Examples:" msgstr "Exemplos:" +#: ../../library/functions.rst:384 +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:403 msgid "" "If the argument is a string, it must contain either a real part (in the same " @@ -993,7 +1056,7 @@ msgstr "" "A string pode opcionalmente ser cercada por espaços em branco e parênteses " "``'('`` e ``')'``, que são ignorados. A string não deve conter espaços em " "branco entre os símbolos ``'+'``, ``'-'``, o sufixo ``'j'`` ou ``'J'``, e o " -"número decimal. Por examplo, ``complex('1+2j')`` é ok, mas ``complex('1 + " +"número decimal. Por exemplo, ``complex('1+2j')`` é ok, mas ``complex('1 + " "2j')`` levanta :exc:`ValueError`. Mais precisamente, após descartar os " "parênteses e os espaços em branco do início e do final, a entrada deve ser " "conforme a regra de produção :token:`~float:complexvalue` da gramática a " @@ -1042,8 +1105,8 @@ msgstr "Se todos os argumentos forem omitidos, retorna ``0j``." 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:445 ../../library/functions.rst:802 +#: ../../library/functions.rst:1045 msgid "Grouping digits with underscores as in code literals is allowed." msgstr "" "Agrupar dígitos com sublinhados como em literais de código é permitido." @@ -1216,6 +1279,20 @@ msgstr "" msgid "Equivalent to::" msgstr "Equivalente a::" +#: ../../library/functions.rst:564 +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" @@ -1248,7 +1325,15 @@ msgstr "levanta" msgid "Syntax errors are reported as exceptions." msgstr "Erros de sintaxe são reportados como exceções." -#: ../../library/functions.rst:589 +#: ../../library/functions.rst:591 ../../library/functions.rst:652 +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:594 msgid "" "The *expression* argument is parsed and evaluated as a Python expression " "(technically speaking, a condition list) using the *globals* and *locals* " @@ -1282,11 +1367,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:610 msgid "Example:" msgstr "Exemplo:" -#: ../../library/functions.rst:611 +#: ../../library/functions.rst:616 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 +1383,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:621 msgid "" "Hints: dynamic execution of statements is supported by the :func:`exec` " "function. The :func:`globals` and :func:`locals` functions return the " @@ -1310,7 +1395,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:626 msgid "" "If the given source is a string, then leading and trailing spaces and tabs " "are stripped." @@ -1318,7 +1403,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:629 msgid "" "See :func:`ast.literal_eval` for a function that can safely evaluate strings " "with expressions containing only literals." @@ -1326,8 +1411,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:632 ../../library/functions.rst:634 +#: ../../library/functions.rst:694 ../../library/functions.rst:696 msgid "" "Raises an :ref:`auditing event ` ``exec`` with the code object as " "the argument. Code compilation events may also be raised." @@ -1336,13 +1421,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:639 ../../library/functions.rst:716 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:643 ../../library/functions.rst:720 msgid "" "The semantics of the default *locals* namespace have been adjusted as " "described for the :func:`locals` builtin." @@ -1350,7 +1435,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:655 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 +1459,7 @@ msgstr "" "código passado para a função :func:`exec` . O valor de retorno é sempre " "``None``." -#: ../../library/functions.rst:656 +#: ../../library/functions.rst:666 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 +1478,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:676 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 +1493,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:682 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 +1507,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:688 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:701 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 +1530,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:707 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 +1540,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:711 msgid "Added the *closure* parameter." msgstr "Adicionado o parâmetro *closure*." -#: ../../library/functions.rst:715 +#: ../../library/functions.rst:726 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 +1557,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:732 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 +1569,7 @@ msgstr "" "``None`` e ``(item for item in iterable if item)`` se *function* for " "``None``." -#: ../../library/functions.rst:726 +#: ../../library/functions.rst:737 msgid "" "See :func:`itertools.filterfalse` for the complementary function that " "returns elements of *iterable* for which *function* is false." @@ -1491,13 +1577,37 @@ 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:748 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 " "string." -#: ../../library/functions.rst:754 +#: ../../library/functions.rst:752 +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:765 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 " @@ -1516,7 +1626,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:786 msgid "" "Case is not significant, so, for example, \"inf\", \"Inf\", \"INFINITY\", " "and \"iNfINity\" are all acceptable spellings for positive infinity." @@ -1525,7 +1635,7 @@ msgstr "" "\"INFINITY\" e \"iNfINity\" são todas grafias aceitáveis para o infinito " "positivo." -#: ../../library/functions.rst:778 +#: ../../library/functions.rst:789 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 +1647,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:794 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 +1657,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:798 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:800 msgid "The float type is described in :ref:`typesnumeric`." msgstr "O tipo float é descrito em :ref:`typesnumeric`." -#: ../../library/functions.rst:797 +#: ../../library/functions.rst:808 msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__float__` is not " "defined." @@ -1563,7 +1673,7 @@ msgstr "" "Chamada para :meth:`~object.__index__` se :meth:`~object.__float__` não está " "definido." -#: ../../library/functions.rst:807 +#: ../../library/functions.rst:818 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 +1685,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:823 msgid "" "The default *format_spec* is an empty string which usually gives the same " "effect as calling :func:`str(value) `." @@ -1583,7 +1693,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:826 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 +1709,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:833 msgid "" "``object().__format__(format_spec)`` raises :exc:`TypeError` if " "*format_spec* is not an empty string." @@ -1607,7 +1717,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:842 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 +1727,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:846 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 +1736,7 @@ msgstr "" "`list`, :class:`tuple`, e :class:`dict`, assim como o módulo :mod:" "`collections`." -#: ../../library/functions.rst:843 +#: ../../library/functions.rst:854 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 +1752,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:863 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -1654,7 +1764,7 @@ msgstr "" "atributo privado (atributos com dois sublinhados à esquerda) para recuperá-" "lo com :func:`getattr`." -#: ../../library/functions.rst:860 +#: ../../library/functions.rst:871 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 +1774,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:878 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 +1786,7 @@ msgstr "" "implementado chamando ``getattr(object, name)`` e vendo se levanta um :exc:" "`AttributeError` ou não.)" -#: ../../library/functions.rst:875 +#: ../../library/functions.rst:886 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 +1799,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:893 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 +1808,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:900 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 +1825,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:907 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 +1837,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:912 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:914 msgid "" "Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported signatures " "for callables are now more comprehensive and consistent." @@ -1741,18 +1851,18 @@ 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:921 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 :" -"meth:`~object.__index__` method that returns an integer. Some examples:" +"\"0x\". If *integer* is not a Python :class:`int` object, it has to define " +"an :meth:`~object.__index__` method that returns an integer. Some examples:" msgstr "" "Converte um número inteiro para uma string hexadecimal em letras minúsculas " -"pré-fixada com \"0x\". Se *x* não é um objeto :class:`int` do Python, ele " -"tem que definir um método :meth:`~object.__index__` que retorne um inteiro. " -"Alguns exemplos:" +"prefixada com \"0x\". Se *integer* não é um objeto :class:`int` do Python, " +"ele tem que definir um método :meth:`~object.__index__` que retorne um " +"inteiro. Alguns exemplos:" -#: ../../library/functions.rst:919 +#: ../../library/functions.rst:930 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 +1872,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:942 msgid "" "See also :func:`int` for converting a hexadecimal string to an integer using " "a base of 16." @@ -1770,7 +1880,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:947 msgid "" "To obtain a hexadecimal string representation for a float, use the :meth:" "`float.hex` method." @@ -1778,7 +1888,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:953 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 +1900,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:958 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:960 msgid "" "Raises an :ref:`auditing event ` ``builtins.id`` with argument " "``id``." @@ -1802,7 +1912,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``builtins.id`` com o " "argumento ``id``." -#: ../../library/functions.rst:955 +#: ../../library/functions.rst:966 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 +1925,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:971 +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:976 msgid "" "If the :mod:`readline` module was loaded, then :func:`input` will use it to " "provide elaborate line editing and history features." @@ -1823,7 +1945,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:979 ../../library/functions.rst:981 msgid "" "Raises an :ref:`auditing event ` ``builtins.input`` with argument " "``prompt`` before reading input" @@ -1831,7 +1953,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:984 ../../library/functions.rst:986 msgid "" "Raises an :ref:`auditing event ` ``builtins.input/result`` with " "the result after successfully reading input." @@ -1839,7 +1961,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:993 msgid "" "Return an integer object constructed from a number or a string, or return " "``0`` if no arguments are given." @@ -1847,7 +1969,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:998 +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:1013 msgid "" "If the argument defines :meth:`~object.__int__`, ``int(x)`` returns ``x." "__int__()``. If the argument defines :meth:`~object.__index__`, it returns " @@ -1861,7 +2011,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:1019 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 +2026,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:1025 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 +2051,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:1036 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:1038 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 +2068,11 @@ msgstr "" "`base.__int__ ` ao invés de :meth:`base.__index__ `." -#: ../../library/functions.rst:1037 +#: ../../library/functions.rst:1048 msgid "The first parameter is now positional-only." msgstr "O primeiro parâmetro agora é somente-posicional." -#: ../../library/functions.rst:1040 +#: ../../library/functions.rst:1051 msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__int__` is not " "defined." @@ -1930,11 +2080,11 @@ msgstr "" "Chamada para :meth:`~object.__index__` se :meth:`~object.__int__` não está " "definido." -#: ../../library/functions.rst:1043 +#: ../../library/functions.rst:1054 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:1057 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 +2100,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:1068 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,39 +2143,39 @@ msgstr "" "*classinfo*. Em qualquer outro caso, é levantada uma exceção :exc:" "`TypeError`." -#: ../../library/functions.rst:1088 +#: ../../library/functions.rst:1100 msgid "" "Return an :term:`iterator` object. The first argument is interpreted very " "differently depending on the presence of the second argument. Without a " -"second argument, *object* must be a collection object which supports the :" -"term:`iterable` protocol (the :meth:`~object.__iter__` method), or it must " -"support the sequence protocol (the :meth:`~object.__getitem__` method with " -"integer arguments starting at ``0``). If it does not support either of " -"those protocols, :exc:`TypeError` is raised. If the second argument, " -"*sentinel*, is given, then *object* must be a callable object. The iterator " -"created in this case will call *object* with no arguments for each call to " -"its :meth:`~iterator.__next__` method; if the value returned is equal to " -"*sentinel*, :exc:`StopIteration` will be raised, otherwise the value will be " -"returned." +"second argument, the single argument must be a collection object which " +"supports the :term:`iterable` protocol (the :meth:`~object.__iter__` " +"method), or it must support the sequence protocol (the :meth:`~object." +"__getitem__` method with integer arguments starting at ``0``). If it does " +"not support either of those protocols, :exc:`TypeError` is raised. If the " +"second argument, *sentinel*, is given, then the first argument must be a " +"callable object. The iterator created in this case will call *callable* " +"with no arguments for each call to its :meth:`~iterator.__next__` method; if " +"the value returned is equal to *sentinel*, :exc:`StopIteration` will be " +"raised, otherwise the value will be returned." msgstr "" "Retorna um objeto :term:`iterador`. O primeiro argumento é interpretado " "muito diferentemente dependendo da presença do segundo argumento. Sem um " -"segundo argumento, *object* deve ser uma coleção de objetos com suporte ao " -"protocolo :term:`iterável` (o método :meth:`~object.__iter__`), ou ele deve " -"ter suporte ao protocolo de sequência (o método :meth:`~object.__getitem__` " -"com argumentos inteiros começando em ``0``). Se ele não tem suporte nenhum " -"desses protocolos, uma :exc:`TypeError` é levantada. Se o segundo argumento, " -"*sentinel*, é fornecido, então *object* deve ser um objeto chamável. O " -"iterador criado neste caso irá chamar *object* sem nenhum argumento para " -"cada chamada para o seu método :meth:`~iterator.__next__`; se o valor " -"devolvido é igual a *sentinel*, então :exc:`StopIteration` será levantado, " -"caso contrário o valor será devolvido." - -#: ../../library/functions.rst:1102 +"segundo argumento, o primeiro argumento deve ser uma coleção de objetos com " +"suporte ao protocolo :term:`iterável` (o método :meth:`~object.__iter__`), " +"ou ele deve ter suporte ao protocolo de sequência (o método :meth:`~object." +"__getitem__` com argumentos inteiros começando em ``0``). Se ele não tem " +"suporte nenhum desses protocolos, uma :exc:`TypeError` é levantada. Se o " +"segundo argumento, *sentinel*, é fornecido, então o primeiro argumento deve " +"ser um objeto chamável. O iterador criado neste caso irá chamar *callable* " +"sem nenhum argumento para cada chamada para o seu método :meth:`~iterator." +"__next__`; se o valor devolvido é igual a *sentinel*, então :exc:" +"`StopIteration` será levantado, caso contrário o valor será devolvido." + +#: ../../library/functions.rst:1114 msgid "See also :ref:`typeiter`." msgstr "Veja também :ref:`typeiter`." -#: ../../library/functions.rst:1104 +#: ../../library/functions.rst:1116 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 +2185,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:1120 +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:1128 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 +2207,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:1134 msgid "" "``len`` raises :exc:`OverflowError` on lengths larger than :data:`sys." "maxsize`, such as :class:`range(2 ** 100) `." @@ -2053,7 +2215,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:1142 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 +2223,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:1148 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 +2233,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:1152 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 +2243,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:1156 msgid "" "At class scope, it returns the namespace that will be passed to the " "metaclass constructor." @@ -2089,7 +2251,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:1159 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 +2259,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:1162 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 +2275,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:1169 msgid "" "In an :term:`optimized scope` (including functions, generators, and " "coroutines), each call to ``locals()`` instead returns a fresh dictionary " @@ -2134,7 +2296,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:1178 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 +2310,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:1184 msgid "" "Calling ``locals()`` as part of a generator expression is equivalent to " "calling it in a nested generator function." @@ -2156,7 +2318,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:1187 msgid "" "The behaviour of ``locals()`` in a comprehension has been updated as " "described in :pep:`709`." @@ -2164,7 +2326,7 @@ msgstr "" "O comportamento de ``locals()`` em uma compreensão foi atualizado conforme " "descrito na :pep:`709`." -#: ../../library/functions.rst:1180 +#: ../../library/functions.rst:1191 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 +2340,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:1201 msgid "" "Return an iterator that applies *function* to every item of *iterable*, " "yielding the results. If additional *iterables* arguments are passed, " @@ -2195,14 +2357,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:1213 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:1216 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 +2374,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:1221 ../../library/functions.rst:1259 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 +2389,7 @@ msgstr "" "vazio, e *default* não foi fornecido, uma exceção :exc:`ValueError` é " "levantada." -#: ../../library/functions.rst:1216 +#: ../../library/functions.rst:1227 msgid "" "If multiple items are maximal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2239,15 +2401,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:1232 ../../library/functions.rst:1270 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:1235 ../../library/functions.rst:1273 msgid "The *key* can be ``None``." msgstr "O valor de *key* pode ser ``None``." -#: ../../library/functions.rst:1232 +#: ../../library/functions.rst:1243 msgid "" "Return a \"memory view\" object created from the given argument. See :ref:" "`typememoryview` for more information." @@ -2255,14 +2417,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:1251 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:1254 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 +2434,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:1265 msgid "" "If multiple items are minimal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2284,7 +2446,7 @@ msgstr "" "estabilidade, tais como ``sorted(iterable, key=keyfunc)[0]`` e ``heapq." "nsmallest(1, iterable, key=keyfunc)``." -#: ../../library/functions.rst:1269 +#: ../../library/functions.rst:1280 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,38 +2457,40 @@ msgstr "" "iterável tenha sido percorrido por completo, caso contrário :exc:" "`StopIteration` é levantada." -#: ../../library/functions.rst:1276 +#: ../../library/functions.rst:1287 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:1294 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:1301 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` " -"object, it has to define an :meth:`~object.__index__` method that returns an " -"integer. For example:" +"result is a valid Python expression. If *integer* is not a Python :class:" +"`int` object, it has to define an :meth:`~object.__index__` method that " +"returns an integer. For example:" msgstr "" -"Converte um número inteiro para uma string em base octal, pré-fixada com " -"\"0o\". O resultado é uma expressão Python válida. Se *x* não for um objeto :" -"class:`int` Python, ele tem que definir um método :meth:`~object.__index__` " -"que devolve um inteiro. Por exemplo:" +"Converte um número inteiro para uma string em base octal, prefixada com " +"\"0o\". O resultado é uma expressão Python válida. Se *integer* não for um " +"objeto :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:1311 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 +2498,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:1328 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 +2508,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:1332 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 +2522,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:1338 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 +2531,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 +2542,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:1355 msgid "Character" msgstr "Caractere" -#: ../../library/functions.rst:1342 +#: ../../library/functions.rst:1355 msgid "Meaning" msgstr "Significado" -#: ../../library/functions.rst:1344 +#: ../../library/functions.rst:1357 msgid "``'r'``" msgstr "``'r'``" -#: ../../library/functions.rst:1344 +#: ../../library/functions.rst:1357 msgid "open for reading (default)" msgstr "abre para leitura (padrão)" -#: ../../library/functions.rst:1345 +#: ../../library/functions.rst:1358 msgid "``'w'``" msgstr "``'w'``" -#: ../../library/functions.rst:1345 +#: ../../library/functions.rst:1358 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:1359 msgid "``'x'``" msgstr "``'x'``" -#: ../../library/functions.rst:1346 +#: ../../library/functions.rst:1359 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:1360 msgid "``'a'``" msgstr "``'a'``" -#: ../../library/functions.rst:1347 +#: ../../library/functions.rst:1360 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:1361 msgid "``'b'``" msgstr "``'b'``" -#: ../../library/functions.rst:1348 ../../library/functions.rst:1492 +#: ../../library/functions.rst:1361 ../../library/functions.rst:1505 msgid "binary mode" msgstr "modo binário" -#: ../../library/functions.rst:1349 +#: ../../library/functions.rst:1362 msgid "``'t'``" msgstr "``'t'``" -#: ../../library/functions.rst:1349 +#: ../../library/functions.rst:1362 msgid "text mode (default)" msgstr "modo texto (padrão)" -#: ../../library/functions.rst:1350 +#: ../../library/functions.rst:1363 msgid "``'+'``" msgstr "``'+'``" -#: ../../library/functions.rst:1350 +#: ../../library/functions.rst:1363 msgid "open for updating (reading and writing)" msgstr "aberto para atualização (leitura e escrita)" -#: ../../library/functions.rst:1353 +#: ../../library/functions.rst:1366 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 +2622,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:1370 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 +2641,7 @@ msgstr "" "dependente da plataforma, ou usando a codificação definida em *encoding* se " "fornecida." -#: ../../library/functions.rst:1367 +#: ../../library/functions.rst:1380 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 +2651,7 @@ msgstr "" "texto; todo processamento é feito pelo próprio Python, e é então " "independente de plataforma." -#: ../../library/functions.rst:1371 +#: ../../library/functions.rst:1384 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 +2675,7 @@ msgstr "" "*buffering* é fornecido, a política de buffering padrão funciona da seguinte " "forma:" -#: ../../library/functions.rst:1381 +#: ../../library/functions.rst:1394 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 +2688,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:1399 msgid "" "\"Interactive\" text files (files for which :meth:`~io.IOBase.isatty` " "returns ``True``) use line buffering. Other text files use the policy " @@ -2534,7 +2698,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:1403 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 +2712,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:1409 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 +2727,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:1417 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 +2735,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:1421 msgid "" "``'ignore'`` ignores errors. Note that ignoring encoding errors can lead to " "data loss." @@ -2579,7 +2743,7 @@ msgstr "" "``'ignore'`` ignora erros. Note que ignorar erros de código pode levar à " "perda de dados." -#: ../../library/functions.rst:1411 +#: ../../library/functions.rst:1424 msgid "" "``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted " "where there is malformed data." @@ -2587,7 +2751,7 @@ msgstr "" "``'replace'`` faz um marcador de substituição (tal como ``'?'``) ser " "inserido onde existem dados malformados." -#: ../../library/functions.rst:1414 +#: ../../library/functions.rst:1427 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 +2765,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:1434 msgid "" "``'xmlcharrefreplace'`` is only supported when writing to a file. Characters " "not supported by the encoding are replaced with the appropriate XML " @@ -2611,7 +2775,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:1438 msgid "" "``'backslashreplace'`` replaces malformed data by Python's backslashed " "escape sequences." @@ -2619,7 +2783,7 @@ msgstr "" "``'backslashreplace'`` substitui dados malformados pela sequência de escape " "utilizando contrabarra do Python." -#: ../../library/functions.rst:1428 +#: ../../library/functions.rst:1441 msgid "" "``'namereplace'`` (also only supported when writing) replaces unsupported " "characters with ``\\N{...}`` escape sequences." @@ -2627,7 +2791,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:1449 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 +2801,7 @@ msgstr "" "pode ser ``None``, ``''``, ``'\\n'``, ``'\\r'`` e ``'\\r\\n'``. Ele funciona " "da seguinte forma:" -#: ../../library/functions.rst:1440 +#: ../../library/functions.rst:1453 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 +2820,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:1461 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 +2834,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:1467 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 +2846,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:1472 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 +2860,11 @@ msgstr "" "arquivo aberto (passando :mod:`os.open` como *opener* resulta em " "funcionalidade semelhante à passagem de ``None``)." -#: ../../library/functions.rst:1465 +#: ../../library/functions.rst:1478 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:1480 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 +2872,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:1483 +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:1493 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 +2921,7 @@ msgstr "" "bruto, uma subclasse de :class:`io.RawIOBase`, :class:`io.FileIO`, é " "retornado." -#: ../../library/functions.rst:1501 +#: ../../library/functions.rst:1514 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 +2931,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:1518 msgid "" "Raises an :ref:`auditing event ` ``open`` with arguments ``path``, " "``mode``, ``flags``." @@ -2753,7 +2939,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``open`` com os argumentos " "``path``, ``mode``, ``flags``." -#: ../../library/functions.rst:1507 +#: ../../library/functions.rst:1520 msgid "" "The ``mode`` and ``flags`` arguments may have been modified or inferred from " "the original call." @@ -2761,21 +2947,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:1525 msgid "The *opener* parameter was added." msgstr "O parâmetro *opener* foi adicionado." -#: ../../library/functions.rst:1513 +#: ../../library/functions.rst:1526 msgid "The ``'x'`` mode was added." msgstr "O modo ``'x'`` foi adicionado." -#: ../../library/functions.rst:1514 +#: ../../library/functions.rst:1527 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:1528 msgid "" ":exc:`FileExistsError` is now raised if the file opened in exclusive " "creation mode (``'x'``) already exists." @@ -2783,11 +2969,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:1533 msgid "The file is now non-inheritable." msgstr "O arquivo agora é não herdável." -#: ../../library/functions.rst:1524 +#: ../../library/functions.rst:1537 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 +2984,16 @@ msgstr "" "levantar uma exceção :exc:`InterruptedError` (consulte :pep:`475` para " "entender a justificativa)." -#: ../../library/functions.rst:1527 +#: ../../library/functions.rst:1540 msgid "The ``'namereplace'`` error handler was added." msgstr "O tratador de erros ``'namereplace'`` foi adicionado." -#: ../../library/functions.rst:1531 +#: ../../library/functions.rst:1544 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:1545 msgid "" "On Windows, opening a console buffer may return a subclass of :class:`io." "RawIOBase` other than :class:`io.FileIO`." @@ -2815,23 +3001,37 @@ 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:1548 msgid "The ``'U'`` mode has been removed." msgstr "O modo ``'U'`` foi removido." -#: ../../library/functions.rst:1540 +#: ../../library/functions.rst:1553 +msgid "Return the ordinal value of a character." +msgstr "Retorna o valor ordinal de um caractere." + +#: ../../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, " -"``ord('a')`` returns the integer ``97`` and ``ord('€')`` (Euro sign) returns " -"``8364``. This is the inverse of :func:`chr`." +"If the argument is a one-character string, return the Unicode code point of " +"that character. For example, ``ord('a')`` returns the integer ``97`` and " +"``ord('€')`` (Euro sign) returns ``8364``. This is the inverse of :func:" +"`chr`." msgstr "" -"Dada uma string que representa um caractere Unicode, retorna um número " -"inteiro representando o ponto de código Unicode desse caractere. Por " -"exemplo, ``ord('a')`` retorna o número inteiro ``97`` e ``ord('€')`` (sinal " -"do Euro) retorna ``8364``. Este é o inverso de :func:`chr`." +"Se o argumento for uma string de um caractere, retorna o ponto de código " +"Unicode desse caractere.. Por 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:1560 +msgid "" +"If the argument is a :class:`bytes` or :class:`bytearray` object of length " +"1, return its single byte value. For example, ``ord(b'a')`` returns the " +"integer ``97``." +msgstr "" +"Se o argumento for um objeto :class:`bytes` ou :class:`bytearray` de " +"comprimento 1, retorna seu valor de byte único. Por exemplo, ``ord(b'a')`` " +"retorna o inteiro ``97``." + +#: ../../library/functions.rst:1567 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,9 +3043,9 @@ 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:1572 msgid "" -"The arguments must have numeric types. With mixed operand types, the " +"When arguments are builtin numeric types with mixed operand types, the " "coercion rules for binary arithmetic operators apply. For :class:`int` " "operands, the result has the same type as the operands (after coercion) " "unless the second argument is negative; in that case, all arguments are " @@ -2857,20 +3057,20 @@ msgid "" "`float` with an integral exponent, a float result is delivered. For example, " "``pow(-9, 2.0)`` returns ``81.0``." msgstr "" -"Os argumentos devem ter tipos numéricos. Com tipos de operandos mistos, " -"aplicam-se as regras de coerção para operadores aritméticos binários. Para " -"operandos :class:`int`, o resultado tem o mesmo tipo que os operandos (após " -"coerção), a menos que o segundo argumento seja negativo; nesse caso, todos " -"os argumentos são convertidos em ponto flutuante e um resultado ponto " -"flutuante é entregue. Por exemplo, ``pow(10, 2)`` retorna ``100``, mas " -"``pow(10, -2)`` retorna ``0.01``. Para uma base negativa do tipo :class:" -"`int` ou :class:`float` e um expoente não integral, um resultado complexo é " -"entregue. Por exemplo, ``pow(-9, 0.5)`` retorna um valor próximo a ``3j``. " -"Enquanto isso, para uma base negativa do tipo :class:`int` ou :class:`float` " -"com um expoente integral, um resultado de ponto flutuante é retornado. Por " -"exemplo, ``pow(-9, 2.0)`` retorna ``81.0``." - -#: ../../library/functions.rst:1565 +"Quando argumentos são tipos numéricos embutidos com tipos de operandos " +"mistos, aplicam-se as regras de coerção para operadores aritméticos " +"binários. Para operandos :class:`int`, o resultado tem o mesmo tipo que os " +"operandos (após coerção), a menos que o segundo argumento seja negativo; " +"nesse caso, todos os argumentos são convertidos em ponto flutuante e um " +"resultado ponto flutuante é entregue. Por exemplo, ``pow(10, 2)`` retorna " +"``100``, mas ``pow(10, -2)`` retorna ``0.01``. Para uma base negativa do " +"tipo :class:`int` ou :class:`float` e um expoente não integral, um resultado " +"complexo é entregue. Por exemplo, ``pow(-9, 0.5)`` retorna um valor próximo " +"a ``3j``. Enquanto isso, para uma base negativa do tipo :class:`int` ou :" +"class:`float` com um expoente integral, um resultado de ponto flutuante é " +"retornado. Por exemplo, ``pow(-9, 2.0)`` retorna ``81.0``." + +#: ../../library/functions.rst:1584 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 +3084,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:1590 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:1592 +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:1597 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 +3110,14 @@ msgstr "" "permite que o segundo argumento seja negativo, permitindo o cálculo de " "inversos modulares." -#: ../../library/functions.rst:1583 +#: ../../library/functions.rst:1602 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:1609 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 +3127,7 @@ msgstr "" "por *end*. *sep*, *end*, *file* e *flush*, se houver, devem ser fornecidos " "como argumentos nomeados." -#: ../../library/functions.rst:1594 +#: ../../library/functions.rst:1613 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 +3141,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:1619 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 +3151,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:1624 msgid "" "Output buffering is usually determined by *file*. However, if *flush* is " "true, the stream is forcibly flushed." @@ -2950,15 +3162,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:1628 msgid "Added the *flush* keyword argument." msgstr "Adicionado o argumento nomeado *flush*." -#: ../../library/functions.rst:1615 +#: ../../library/functions.rst:1634 msgid "Return a property attribute." msgstr "Retorna um atributo de propriedade." -#: ../../library/functions.rst:1617 +#: ../../library/functions.rst:1636 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 +3180,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:1640 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 +#: ../../library/functions.rst:1642 +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:1657 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:1660 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 +3236,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:1664 +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:1673 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 +3266,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:1681 msgid "" "A property object has ``getter``, ``setter``, and ``deleter`` methods usable " "as decorators that create a copy of the property with the corresponding " @@ -3016,6 +3280,42 @@ msgstr "" #: ../../library/functions.rst:1686 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:1705 +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 " "case.)" @@ -3024,7 +3324,7 @@ msgstr "" "nas funções adicionais usar o mesmo nome que a property original (``x`` " "neste caso)." -#: ../../library/functions.rst:1690 +#: ../../library/functions.rst:1709 msgid "" "The returned property object also has the attributes ``fget``, ``fset``, and " "``fdel`` corresponding to the constructor arguments." @@ -3032,11 +3332,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:1712 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:1717 +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:1728 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 +3352,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:1734 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,24 +3374,42 @@ msgstr "" "Se :func:`sys.displayhook` não estiver acessível, esta função vai levantar :" "exc:`RuntimeError`." -#: ../../library/functions.rst:1719 +#: ../../library/functions.rst:1745 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:1747 +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:1758 msgid "" -"Return a reverse :term:`iterator`. *seq* must be an object which has a :" -"meth:`~object.__reversed__` method or supports the sequence protocol (the :" -"meth:`~object.__len__` method and the :meth:`~object.__getitem__` method " -"with integer arguments starting at ``0``)." +"Return a reverse :term:`iterator`. The argument must be an object which has " +"a :meth:`~object.__reversed__` method or supports the sequence protocol " +"(the :meth:`~object.__len__` method and the :meth:`~object.__getitem__` " +"method with integer arguments starting at ``0``)." msgstr "" -"Retorna um :term:`iterador ` reverso. *seq* deve ser um objeto que " -"possui o método :meth:`~object.__reversed__` ou suporta o protocolo de " -"sequência (o método :meth:`~object.__len__` e o método :meth:`~object." -"__getitem__` com argumentos inteiros começando em ``0``)." +"Retorna um :term:`iterador` reverso. *seq* deve ser um objeto que possui o " +"método :meth:`~object.__reversed__` ou suporta o protocolo de 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:1766 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 +3419,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:1770 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 +3438,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:1779 msgid "" "For a general Python object ``number``, ``round`` delegates to ``number." "__round__``." @@ -3120,7 +3446,7 @@ msgstr "" "Para um objeto Python geral ``number``, ``round`` delega para ``number." "__round__``." -#: ../../library/functions.rst:1758 +#: ../../library/functions.rst:1784 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 +3460,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:1795 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 +3470,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:1799 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 +3480,7 @@ msgstr "" "class:`list`, :class:`tuple` e :class:`dict`, bem como o módulo :mod:" "`collections`." -#: ../../library/functions.rst:1781 +#: ../../library/functions.rst:1806 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 +3494,7 @@ msgstr "" "permita. Por exemplo, ``setattr(x, 'foobar', 123)`` é equivalente a ``x." "foobar = 123``." -#: ../../library/functions.rst:1787 +#: ../../library/functions.rst:1812 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 +3509,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:1820 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -3194,7 +3520,7 @@ msgstr "" "atributo privado (atributos com dois sublinhados à esquerda) para defini-lo " "com :func:`setattr`." -#: ../../library/functions.rst:1804 +#: ../../library/functions.rst:1829 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 +3530,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:1833 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 +3542,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:1842 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 +3553,7 @@ msgstr "" "func:`itertools.islice` para uma versão alternativa que retorna um :term:" "`iterador`." -#: ../../library/functions.rst:1822 +#: ../../library/functions.rst:1847 msgid "" "Slice objects are now :term:`hashable` (provided :attr:`~slice.start`, :attr:" "`~slice.stop`, and :attr:`~slice.step` are hashable)." @@ -3235,18 +3561,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:1853 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:1855 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:1857 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 +3582,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:1861 msgid "" "*reverse* is a boolean value. If set to ``True``, then the list elements " "are sorted as if each comparison were reversed." @@ -3265,7 +3591,7 @@ msgstr "" "elementos da lista são classificados como se cada comparação estivesse " "invertida." -#: ../../library/functions.rst:1839 +#: ../../library/functions.rst:1864 msgid "" "Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a " "*key* function." @@ -3273,7 +3599,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:1867 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 +3611,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:1872 msgid "" "The sort algorithm uses only ``<`` comparisons between items. While " "defining an :meth:`~object.__lt__` method will suffice for sorting, :PEP:`8` " @@ -3293,7 +3619,7 @@ msgid "" "implemented. This will help avoid bugs when using the same data with other " "ordering tools such as :func:`max` that rely on a different underlying " "method. Implementing all six comparisons also helps avoid confusion for " -"mixed type comparisons which can call reflected the :meth:`~object.__gt__` " +"mixed type comparisons which can call the reflected :meth:`~object.__gt__` " "method." msgstr "" "O algoritmo de classificação usa apenas comparações ``<`` entre itens. " @@ -3303,20 +3629,20 @@ msgstr "" "mesmos dados com outras ferramentas de ordenação, como :func:`max`, que " "dependem de um método subjacente diferente. Implementar todas as seis " "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__`." +"que podem chamar o método espelhado :meth:`~object.__gt__`." -#: ../../library/functions.rst:1856 +#: ../../library/functions.rst:1881 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:1885 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:1887 msgid "" "A static method does not receive an implicit first argument. To declare a " "static method, use this idiom::" @@ -3324,7 +3650,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:1890 +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:1894 msgid "" "The ``@staticmethod`` form is a function :term:`decorator` -- see :ref:" "`function` for details." @@ -3332,7 +3668,7 @@ msgstr "" "A forma ``@staticmethod`` é uma função de :term:`decorador` -- veja :ref:" "`function` para detalhes." -#: ../../library/functions.rst:1872 +#: ../../library/functions.rst:1897 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 +3680,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:1902 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 +3690,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:1906 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 +3704,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:1912 +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:1918 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:1920 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:1938 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:1940 msgid "" "``str`` is the built-in string :term:`class`. For general information about " "strings, see :ref:`textseq`." @@ -3397,7 +3749,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:1946 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 +3759,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:1950 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 +3773,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:1956 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:1959 msgid "" "Summation of floats switched to an algorithm that gives higher accuracy and " "better commutativity on most builds." @@ -3433,7 +3785,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:1966 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 +3795,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:1970 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 +3803,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:1974 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:1978 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:1983 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 +3837,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:1988 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 +3854,7 @@ msgstr "" "esperado em funções aninhadas, incluindo expressões geradoras, que criam " "funções aninhadas implicitamente.)" -#: ../../library/functions.rst:1967 +#: ../../library/functions.rst:1995 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 +3862,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:2000 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 +3889,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:2010 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:2012 +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:2017 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 +3916,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:2021 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 +3933,7 @@ msgstr "" "definida para procuras implícitas usando instruções ou operadores como " "``super()[name]``." -#: ../../library/functions.rst:2001 +#: ../../library/functions.rst:2029 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 +3950,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:2036 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:2045 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 +3968,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:2054 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:2058 msgid "" "The :func:`isinstance` built-in function is recommended for testing the type " "of an object, because it takes subclasses into account." @@ -3622,33 +3986,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:2061 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:2076 +msgid "See also:" +msgstr "Veja também:" -#: ../../library/functions.rst:2052 +#: ../../library/functions.rst:2078 +msgid "" +":ref:`Documentation on attributes and methods on classes `." +msgstr "" +":ref:`Documentação sobre atributos e métodos em classes `." + +#: ../../library/functions.rst:2079 +msgid ":ref:`bltin-type-objects`" +msgstr ":ref:`bltin-type-objects`" + +#: ../../library/functions.rst:2081 msgid "" "Keyword arguments provided to the three argument form are passed to the " "appropriate metaclass machinery (usually :meth:`~object.__init_subclass__`) " @@ -3660,44 +4036,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:2086 msgid "See also :ref:`class-customization`." msgstr "Veja também :ref:`class-customization`." -#: ../../library/functions.rst:2059 +#: ../../library/functions.rst:2088 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:2095 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:2098 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:2103 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:2105 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 +4082,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:2111 msgid "" "The result of calling this function without an argument has been updated as " "described for the :func:`locals` builtin." @@ -3715,7 +4090,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:2117 msgid "" "Iterate over several iterables in parallel, producing tuples with an item " "from each one." @@ -3723,11 +4098,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:2120 msgid "Example::" msgstr "Exemplo::" -#: ../../library/functions.rst:2100 +#: ../../library/functions.rst:2122 +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:2129 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 +4128,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:2132 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:2136 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 +4148,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:2140 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 +4160,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:2145 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 +4170,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:2149 +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:2152 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 +4188,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:2156 +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:2159 msgid "" "Unlike the default behavior, it raises a :exc:`ValueError` if one iterable " "is exhausted before the others:" @@ -3796,7 +4204,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:2177 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 +4214,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:2181 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 +4224,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:2185 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 +4232,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:2188 msgid "Tips and tricks:" msgstr "Dicas e truques:" -#: ../../library/functions.rst:2161 +#: ../../library/functions.rst:2190 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 +4251,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:2196 msgid "" ":func:`zip` in conjunction with the ``*`` operator can be used to unzip a " "list::" @@ -3851,11 +4259,29 @@ msgstr "" ":func:`zip` em conjunto com o operador ``*`` pode ser usado para " "descompactar uma lista::" -#: ../../library/functions.rst:2178 +#: ../../library/functions.rst:2199 +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:2207 msgid "Added the ``strict`` argument." msgstr "Adicionado o argumento ``strict``." -#: ../../library/functions.rst:2190 +#: ../../library/functions.rst:2219 msgid "" "This is an advanced function that is not needed in everyday Python " "programming, unlike :func:`importlib.import_module`." @@ -3863,7 +4289,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:2222 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 +4309,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:2231 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 +4325,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:2238 msgid "" "*level* specifies whether to use absolute or relative imports. ``0`` (the " "default) means only perform absolute imports. Positive values for *level* " @@ -3913,31 +4339,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:2244 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:2249 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:2252 +msgid "spam = __import__('spam', globals(), locals(), [], 0)" +msgstr "spam = __import__('spam', globals(), locals(), [], 0)" + +#: ../../library/functions.rst:2254 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:2256 +msgid "spam = __import__('spam.ham', globals(), locals(), [], 0)" +msgstr "spam = __import__('spam.presunto', globals(), locals(), [], 0)" -#: ../../library/functions.rst:2229 +#: ../../library/functions.rst:2258 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 +4379,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:2261 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:2239 +#: ../../library/functions.rst:2264 +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:2268 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 +4408,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:2272 msgid "" "If you simply want to import a module (potentially within a package) by " "name, use :func:`importlib.import_module`." @@ -3971,7 +4416,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:2275 msgid "" "Negative values for *level* are no longer supported (which also changes the " "default value to 0)." @@ -3979,7 +4424,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:2279 msgid "" "When the command line options :option:`-E` or :option:`-I` are being used, " "the environment variable :envvar:`PYTHONCASEOK` is now ignored." @@ -3987,11 +4432,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:2284 msgid "Footnotes" msgstr "Notas de rodapé" -#: ../../library/functions.rst:2256 +#: ../../library/functions.rst:2285 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 +4450,106 @@ msgstr "" msgid "Boolean" msgstr "Booleano" -#: ../../library/functions.rst:154 ../../library/functions.rst:2025 +#: ../../library/functions.rst:154 ../../library/functions.rst:2052 msgid "type" msgstr "tipo" -#: ../../library/functions.rst:641 +#: ../../library/functions.rst:646 msgid "built-in function" msgstr "função embutida" -#: ../../library/functions.rst:641 +#: ../../library/functions.rst:646 msgid "exec" msgstr "exec" -#: ../../library/functions.rst:733 +#: ../../library/functions.rst:744 msgid "NaN" msgstr "NaN" -#: ../../library/functions.rst:733 +#: ../../library/functions.rst:744 msgid "Infinity" -msgstr "Infinito" +msgstr "Infinity" -#: ../../library/functions.rst:801 +#: ../../library/functions.rst:812 msgid "__format__" msgstr "__format__" -#: ../../library/functions.rst:801 ../../library/functions.rst:1902 +#: ../../library/functions.rst:812 ../../library/functions.rst:1928 msgid "string" msgstr "string" -#: ../../library/functions.rst:801 +#: ../../library/functions.rst:812 msgid "format() (built-in function)" msgstr "format() (função embutida)" -#: ../../library/functions.rst:1310 +#: ../../library/functions.rst:1323 msgid "file object" msgstr "objeto arquivo" -#: ../../library/functions.rst:1310 ../../library/functions.rst:1431 +#: ../../library/functions.rst:1323 ../../library/functions.rst:1444 msgid "open() built-in function" msgstr "função embutida open()" -#: ../../library/functions.rst:1338 +#: ../../library/functions.rst:1351 msgid "file" msgstr "arquivo" -#: ../../library/functions.rst:1338 +#: ../../library/functions.rst:1351 msgid "modes" msgstr "modos" -#: ../../library/functions.rst:1431 +#: ../../library/functions.rst:1444 msgid "universal newlines" msgstr "novas linhas universais" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "line-buffered I/O" msgstr "E/S com buffer de linha" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "unbuffered I/O" msgstr "E/S sem buffer" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "buffer size, I/O" msgstr "buffer, tamanho, E/S" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "I/O control" msgstr "controle de E/S" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "buffering" msgstr "buffering" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "text mode" msgstr "texto, modo" -#: ../../library/functions.rst:1492 ../../library/functions.rst:2184 +#: ../../library/functions.rst:1505 ../../library/functions.rst:2213 msgid "module" msgstr "módulo" -#: ../../library/functions.rst:1492 +#: ../../library/functions.rst:1505 msgid "sys" msgstr "sys" -#: ../../library/functions.rst:1902 +#: ../../library/functions.rst:1928 msgid "str() (built-in function)" msgstr "str() (função embutida)" -#: ../../library/functions.rst:2025 +#: ../../library/functions.rst:2052 msgid "object" msgstr "objeto" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2213 msgid "statement" msgstr "instrução" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2213 msgid "import" -msgstr "importação" +msgstr "import" -#: ../../library/functions.rst:2184 +#: ../../library/functions.rst:2213 msgid "builtins" msgstr "builtins" diff --git a/library/functools.po b/library/functools.po index d9f791c79..7d4f65f11 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 +# python-doc bot, 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,28 @@ 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 +#: ../../library/functools.rst:39 ../../library/functools.rst:297 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) # no new calls, just returns the cached result\n" +"120\n" +">>> factorial(12) # two new recursive calls, factorial(10) is 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 " @@ -103,10 +109,22 @@ msgstr "" "instâncias que são efetivamente imutáveis." #: ../../library/functools.rst:70 ../../library/functools.rst:142 -#: ../../library/functools.rst:383 +#: ../../library/functools.rst:389 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 +218,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 +264,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 " @@ -274,23 +304,21 @@ msgid "" "has no effect." msgstr "" -#: ../../library/functools.rst:202 +#: ../../library/functools.rst:205 msgid "" "To help measure the effectiveness of the cache and tune the *maxsize* " -"parameter, the wrapped function is instrumented with a :func:`cache_info` " +"parameter, the wrapped function is instrumented with a :func:`!cache_info` " "function that returns a :term:`named tuple` showing *hits*, *misses*, " "*maxsize* and *currsize*." msgstr "" -#: ../../library/functools.rst:207 +#: ../../library/functools.rst:213 msgid "" -"The decorator also provides a :func:`cache_clear` function for clearing or " +"The decorator also provides a :func:`!cache_clear` function for clearing or " "invalidating the cache." msgstr "" -"O decorador também fornece uma função :func:`cache_clear` para limpar ou " -"invalidar o cache." -#: ../../library/functools.rst:210 +#: ../../library/functools.rst:216 msgid "" "The original underlying function is accessible through the :attr:" "`__wrapped__` attribute. This is useful for introspection, for bypassing " @@ -300,36 +328,29 @@ msgstr "" "`__wrapped__`. Isso é útil para introspecção, para ignorar o cache, ou para " "reinstalar a função com um cache diferente." -#: ../../library/functools.rst:214 +#: ../../library/functools.rst:220 msgid "" "The cache keeps references to the arguments and return values until they age " "out of the cache or until the cache is cleared." msgstr "" -#: ../../library/functools.rst:217 +#: ../../library/functools.rst:223 msgid "" "If a method is cached, the ``self`` instance argument is included in the " "cache. See :ref:`faq-cache-method-calls`" msgstr "" -#: ../../library/functools.rst:220 +#: ../../library/functools.rst:226 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 +#: ../../library/functools.rst:233 msgid "" "In general, the LRU cache should only be used when you want to reuse " "previously computed values. Accordingly, it doesn't make sense to cache " @@ -338,11 +359,31 @@ msgid "" "functions such as time() or random()." msgstr "" -#: ../../library/functools.rst:233 +#: ../../library/functools.rst:239 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:252 +#: ../../library/functools.rst:241 +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:258 msgid "" "Example of efficiently computing `Fibonacci numbers `_ using a cache to implement a `dynamic " @@ -353,33 +394,67 @@ msgstr "" "`programação dinâmica `_ " "técnica::" -#: ../../library/functools.rst:272 +#: ../../library/functools.rst:264 +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:278 msgid "Added the *typed* option." msgstr "Adicionada a opção *typed*." -#: ../../library/functools.rst:275 +#: ../../library/functools.rst:281 msgid "Added the *user_function* option." msgstr "Adicionada a opção *user_function*." -#: ../../library/functools.rst:278 +#: ../../library/functools.rst:284 msgid "Added the function :func:`!cache_parameters`" msgstr "" -#: ../../library/functools.rst:283 +#: ../../library/functools.rst:289 msgid "" "Given a class defining one or more rich comparison ordering methods, this " "class decorator supplies the rest. This simplifies the effort involved in " "specifying all of the possible rich comparison operations:" msgstr "" -#: ../../library/functools.rst:287 +#: ../../library/functools.rst:293 +msgid "" +"The class must define one of :meth:`~object.__lt__`, :meth:`~object." +"__le__`, :meth:`~object.__gt__`, or :meth:`~object.__ge__`. In addition, the " +"class should supply an :meth:`~object.__eq__` method." +msgstr "" + +#: ../../library/functools.rst:299 msgid "" -"The class must define one of :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, " -"or :meth:`__ge__`. In addition, the class should supply an :meth:`__eq__` " -"method." +"@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 +#: ../../library/functools.rst:317 msgid "" "While this decorator makes it easy to create well behaved totally ordered " "types, it *does* come at the cost of slower execution and more complex stack " @@ -388,7 +463,7 @@ msgid "" "rich comparison methods instead is likely to provide an easy speed boost." msgstr "" -#: ../../library/functools.rst:320 +#: ../../library/functools.rst:326 msgid "" "This decorator makes no attempt to override methods that have been declared " "in the class *or its superclasses*. Meaning that if a superclass defines a " @@ -396,13 +471,13 @@ msgid "" "the original method is abstract." msgstr "" -#: ../../library/functools.rst:327 +#: ../../library/functools.rst:333 msgid "" "Returning ``NotImplemented`` from the underlying comparison function for " "unrecognised types is now supported." msgstr "" -#: ../../library/functools.rst:333 +#: ../../library/functools.rst:339 msgid "" "Return a new :ref:`partial object` which when called will " "behave like *func* called with the positional arguments *args* and keyword " @@ -411,7 +486,19 @@ msgid "" "extend and override *keywords*. Roughly equivalent to::" msgstr "" -#: ../../library/functools.rst:349 +#: ../../library/functools.rst:346 +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:355 msgid "" "The :func:`partial` is used for partial function application which " "\"freezes\" some portion of a function's arguments and/or keywords resulting " @@ -420,29 +507,29 @@ msgid "" "where the *base* argument defaults to two:" msgstr "" -#: ../../library/functools.rst:364 +#: ../../library/functools.rst:370 msgid "" "Return a new :class:`partialmethod` descriptor which behaves like :class:" "`partial` except that it is designed to be used as a method definition " "rather than being directly callable." msgstr "" -#: ../../library/functools.rst:368 +#: ../../library/functools.rst:374 msgid "" "*func* must be a :term:`descriptor` or a callable (objects which are both, " "like normal functions, are handled as descriptors)." msgstr "" -#: ../../library/functools.rst:371 +#: ../../library/functools.rst:377 msgid "" "When *func* is a descriptor (such as a normal Python function, :func:" -"`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or another " +"`classmethod`, :func:`staticmethod`, :func:`~abc.abstractmethod` or another " "instance of :class:`partialmethod`), calls to ``__get__`` are delegated to " "the underlying descriptor, and an appropriate :ref:`partial object` returned as the result." msgstr "" -#: ../../library/functools.rst:377 +#: ../../library/functools.rst:383 msgid "" "When *func* is a non-descriptor callable, an appropriate bound method is " "created dynamically. This behaves like a normal Python function when used as " @@ -451,7 +538,28 @@ msgid "" "`partialmethod` constructor." msgstr "" -#: ../../library/functools.rst:408 +#: ../../library/functools.rst:391 +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:414 msgid "" "Apply *function* of two arguments cumulatively to the items of *iterable*, " "from left to right, so as to reduce the iterable to a single value. For " @@ -464,67 +572,204 @@ msgid "" "is returned." msgstr "" -#: ../../library/functools.rst:417 +#: ../../library/functools.rst:423 msgid "Roughly equivalent to::" msgstr "Aproximadamente equivalente a::" -#: ../../library/functools.rst:431 +#: ../../library/functools.rst:425 +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:437 msgid "" "See :func:`itertools.accumulate` for an iterator that yields all " "intermediate values." msgstr "" -#: ../../library/functools.rst:436 +#: ../../library/functools.rst:442 msgid "" "Transform a function into a :term:`single-dispatch ` :term:" "`generic function`." msgstr "" -#: ../../library/functools.rst:439 +#: ../../library/functools.rst:445 msgid "" "To define a generic function, decorate it with the ``@singledispatch`` " "decorator. When defining a function using ``@singledispatch``, note that the " "dispatch happens on the type of the first argument::" msgstr "" -#: ../../library/functools.rst:450 +#: ../../library/functools.rst:449 +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:459 msgid "" -"To add overloaded implementations to the function, use the :func:`register` " +"To add overloaded implementations to the function, use the :func:`!register` " "attribute of the generic function, which can be used as a decorator. For " "functions annotated with types, the decorator will infer the type of the " "first argument automatically::" msgstr "" -#: ../../library/functools.rst:468 +#: ../../library/functools.rst:464 +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:477 msgid ":data:`types.UnionType` and :data:`typing.Union` can also be used::" msgstr "" -#: ../../library/functools.rst:485 +#: ../../library/functools.rst:479 +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:494 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:497 msgid "" -"To enable registering :term:`lambdas` and pre-existing functions, " -"the :func:`register` attribute can also be used in a functional form::" +">>> @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:504 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::" +"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:509 +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:518 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:524 +msgid "" +"To enable registering :term:`lambdas` and pre-existing functions, " +"the :func:`~singledispatch.register` attribute can also be used in a " +"functional form::" +msgstr "" + +#: ../../library/functools.rst:527 +msgid "" +">>> def nothing(arg, verbose=False):\n" +"... print(\"Nothing.\")\n" +"...\n" +">>> fun.register(type(None), nothing)" +msgstr "" + +#: ../../library/functools.rst:532 +msgid "" +"The :func:`~singledispatch.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:536 +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:546 +msgid "" "When called, the generic function dispatches on the type of the first " "argument::" msgstr "" -#: ../../library/functools.rst:538 +#: ../../library/functools.rst:549 +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:566 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 +778,78 @@ msgid "" "found." msgstr "" -#: ../../library/functools.rst:544 +#: ../../library/functools.rst:572 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:576 +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:587 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:590 +msgid "" +">>> fun.dispatch(float)\n" +"\n" +">>> fun.dispatch(dict) # note: default implementation\n" +"" +msgstr "" + +#: ../../library/functools.rst:595 msgid "" "To access all registered implementations, use the read-only ``registry`` " "attribute::" msgstr "" -#: ../../library/functools.rst:581 -msgid "The :func:`register` attribute now supports using type annotations." +#: ../../library/functools.rst:598 +msgid "" +">>> fun.registry.keys()\n" +"dict_keys([, , ,\n" +" , ,\n" +" ])\n" +">>> fun.registry[float]\n" +"\n" +">>> fun.registry[object]\n" +"" msgstr "" -#: ../../library/functools.rst:584 +#: ../../library/functools.rst:609 msgid "" -"The :func:`register` attribute now supports :data:`types.UnionType` and :" -"data:`typing.Union` as type annotations." +"The :func:`~singledispatch.register` attribute now supports using type " +"annotations." msgstr "" -#: ../../library/functools.rst:591 +#: ../../library/functools.rst:612 +msgid "" +"The :func:`~singledispatch.register` attribute now supports :data:`types." +"UnionType` and :data:`typing.Union` as type annotations." +msgstr "" + +#: ../../library/functools.rst:619 msgid "" "Transform a method into a :term:`single-dispatch ` :term:" "`generic function`." msgstr "" -#: ../../library/functools.rst:594 +#: ../../library/functools.rst:622 msgid "" "To define a generic method, decorate it with the ``@singledispatchmethod`` " "decorator. When defining a function using ``@singledispatchmethod``, note " @@ -576,23 +857,57 @@ msgid "" "argument::" msgstr "" -#: ../../library/functools.rst:612 +#: ../../library/functools.rst:627 +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:640 msgid "" "``@singledispatchmethod`` supports nesting with other decorators such as :" -"func:`@classmethod`. Note that to allow for ``dispatcher." -"register``, ``singledispatchmethod`` must be the *outer most* decorator. " -"Here is the ``Negator`` class with the ``neg`` methods bound to the class, " -"rather than an instance of the class::" +"deco:`classmethod`. Note that to allow for ``dispatcher.register``, " +"``singledispatchmethod`` must be the *outer most* decorator. Here is the " +"``Negator`` class with the ``neg`` methods bound to the class, rather than " +"an instance of the class::" +msgstr "" + +#: ../../library/functools.rst:646 +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:634 +#: ../../library/functools.rst:662 msgid "" -"The same pattern can be used for other similar decorators: :func:" -"`@staticmethod`, :func:`@abstractmethod`, " -"and others." +"The same pattern can be used for other similar decorators: :deco:" +"`staticmethod`, :deco:`~abc.abstractmethod`, and others." msgstr "" -#: ../../library/functools.rst:643 +#: ../../library/functools.rst:670 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 +915,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:682 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 +931,7 @@ msgid "" "that refers to the function being wrapped." msgstr "" -#: ../../library/functools.rst:659 +#: ../../library/functools.rst:687 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 +940,7 @@ msgid "" "is typically less than helpful." msgstr "" -#: ../../library/functools.rst:665 +#: ../../library/functools.rst:693 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 +949,26 @@ msgid "" "wrapper function itself is missing any attributes named in *updated*." msgstr "" -#: ../../library/functools.rst:671 +#: ../../library/functools.rst:699 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:704 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:709 +msgid "" +"The :attr:`~function.__type_params__` attribute is now copied by default." msgstr "" -#: ../../library/functools.rst:687 +#: ../../library/functools.rst:715 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 +976,72 @@ msgid "" "updated=updated)``. For example::" msgstr "" -#: ../../library/functools.rst:713 +#: ../../library/functools.rst:720 +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:741 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." +"would have been ``'wrapper'``, and the docstring of the original :func:`!" +"example` would have been lost." msgstr "" -#: ../../library/functools.rst:721 +#: ../../library/functools.rst:749 msgid ":class:`partial` Objects" msgstr "Objetos :class:`partial`" -#: ../../library/functools.rst:723 +#: ../../library/functools.rst:751 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:757 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:763 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:769 msgid "" "The keyword arguments that will be supplied when the :class:`partial` object " "is called." msgstr "" -#: ../../library/functools.rst:744 +#: ../../library/functools.rst:772 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..ec9617245 100644 --- a/library/gc.po +++ b/library/gc.po @@ -1,25 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-25 15:05+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +73,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 @@ -190,8 +191,9 @@ msgid "" "examined. If generation ``0`` has been examined more than *threshold1* " "times since generation ``1`` has been examined, then generation ``1`` is " "examined as well. With the third generation, things are a bit more " -"complicated, see `Collecting the oldest generation `_ for more " +"complicated, see `Collecting the oldest generation `_ for more " "information." msgstr "" "O GC classifica os objetos em três gerações, dependendo de quantas " @@ -206,8 +208,9 @@ msgstr "" "examinada mais de *threshold1* vezes desde que a geração ``1`` foi " "examinada, então a geração ``1`` também é examinada. Com a terceira geração, " "as coisas são um pouco mais complicadas, veja `Coletando a geração mais " -"antiga `_ para mais informações." +"antiga `_ para mais informações." #: ../../library/gc.rst:121 msgid "" @@ -316,6 +319,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 +355,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..d0709ea44 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..b96c69453 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..9a20da6e8 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..6e4db5c53 100644 --- a/library/glob.po +++ b/library/glob.po @@ -1,29 +1,26 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-10-23 15:08+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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,35 +34,40 @@ msgstr "**Código-fonte:** :source:`Lib/glob.py`" #: ../../library/glob.rst:21 msgid "" -"The :mod:`glob` module finds all the pathnames matching a specified pattern " -"according to the rules used by the Unix shell, although results are returned " -"in arbitrary order. No tilde expansion is done, but ``*``, ``?``, and " +"The :mod:`!glob` module finds pathnames using pattern matching rules similar " +"to the Unix shell. No tilde expansion is done, but ``*``, ``?``, and " "character ranges expressed with ``[]`` will be correctly matched. This is " "done by using the :func:`os.scandir` and :func:`fnmatch.fnmatch` functions " "in concert, and not by actually invoking a subshell." msgstr "" -"O módulo :mod:`glob` encontra todos os nomes de caminho que correspondem a " -"um padrão especificado de acordo com as regras usadas pelo shell Unix, " -"embora os resultados sejam retornados em ordem arbitrária. Nenhuma expansão " -"de til é feita, mas ``*``, ``?`` e os intervalos de caracteres expressos com " -"``[]`` serão correspondidos corretamente. Isso é feito usando as funções :" -"func:`os.scandir` e :func:`fnmatch.fnmatch` em conjunto, e não invocando " -"realmente um subshell." - -#: ../../library/glob.rst:28 +"O módulo :mod:`!glob` encontra caminhos usando regras de correspondência de " +"padrões semelhante a do shell Unix. Nenhuma expansão de til é feita, mas " +"``*``, ``?`` e os intervalos de caracteres expressos com ``[]`` serão " +"correspondidos corretamente. Isso é feito usando as funções :func:`os." +"scandir` e :func:`fnmatch.fnmatch` em conjunto, e não invocando realmente um " +"subshell." + +#: ../../library/glob.rst:29 +msgid "" +"The pathnames are returned in no particular order. If you need a specific " +"order, sort the results." +msgstr "" +"Os caminhos são retornados sem uma ordem específica. Se precisar de uma " +"ordem específica, classifique os resultados." + +#: ../../library/glob.rst:32 msgid "" -"Note that files beginning with a dot (``.``) can only be matched by patterns " -"that also start with a dot, unlike :func:`fnmatch.fnmatch` or :func:`pathlib." -"Path.glob`. (For tilde and shell variable expansion, use :func:`os.path." -"expanduser` and :func:`os.path.expandvars`.)" +"Files beginning with a dot (``.``) can only be matched by patterns that also " +"start with a dot, unlike :func:`fnmatch.fnmatch` or :func:`pathlib.Path." +"glob`. For tilde and shell variable expansion, use :func:`os.path." +"expanduser` and :func:`os.path.expandvars`." msgstr "" -"Observe que arquivos iniciados com um ponto (``.``) só podem ser " -"correspondidos com padrões que também iniciam com um ponto, ao contrário de :" -"func:`fnmatch.fnmatch` ou :func:`pathlib.Path.glob`. (Para expansão de til e " -"variável de shell, use :func:`os.path.expanduser` e :func:`os.path." -"expandvars`.)" +"Arquivos iniciando com um ponto (``.``) só podem ser correspondidos com " +"padrões que também iniciam com um ponto, ao contrário de :func:`fnmatch." +"fnmatch` ou :func:`pathlib.Path.glob`. Para expansão de til e variável de " +"shell, use :func:`os.path.expanduser` e :func:`os.path.expandvars`." -#: ../../library/glob.rst:34 +#: ../../library/glob.rst:38 msgid "" "For a literal match, wrap the meta-characters in brackets. For example, " "``'[?]'`` matches the character ``'?'``." @@ -73,11 +75,11 @@ msgstr "" "Para uma correspondência literal, coloque os metacaracteres entre colchetes. " "Por exemplo, ``'[?]'`` corresponde ao caractere ``'?'``." -#: ../../library/glob.rst:37 -msgid "The :mod:`glob` module defines the following functions:" -msgstr "O módulo :mod:`glob` define as seguintes funções:" +#: ../../library/glob.rst:41 +msgid "The :mod:`!glob` module defines the following functions:" +msgstr "O módulo :mod:`!glob` define as seguintes funções:" -#: ../../library/glob.rst:43 +#: ../../library/glob.rst:47 msgid "" "Return a possibly empty list of path names that match *pathname*, which must " "be a string containing a path specification. *pathname* can be either " @@ -98,19 +100,19 @@ msgstr "" "durante a chamada desta função, não é especificado se um nome de caminho " "para esse arquivo será incluído." -#: ../../library/glob.rst:52 +#: ../../library/glob.rst:56 msgid "" "If *root_dir* is not ``None``, it should be a :term:`path-like object` " "specifying the root directory for searching. It has the same effect on :" -"func:`glob` as changing the current directory before calling it. If " +"func:`!glob` as changing the current directory before calling it. If " "*pathname* is relative, the result will contain paths relative to *root_dir*." msgstr "" "Se *root_dir* não for ``None``, deve ser um :term:`objeto caminho ou " "similar` especificando o diretório raiz para pesquisa. Tem o mesmo efeito " -"em :func:`glob` que alterar o diretório atual antes de chamá-lo. Se " +"em :func:`!glob` que alterar o diretório atual antes de chamá-lo. Se " "*pathname* for relativo, o resultado conterá caminhos relativos a *root_dir*." -#: ../../library/glob.rst:58 +#: ../../library/glob.rst:62 msgid "" "This function can support :ref:`paths relative to directory descriptors " "` with the *dir_fd* parameter." @@ -118,7 +120,7 @@ msgstr "" "Esta função oferece suporte para :ref:`caminhos relativos aos descritores de " "diretório ` com o parâmetro *dir_fd*." -#: ../../library/glob.rst:64 +#: ../../library/glob.rst:68 msgid "" "If *recursive* is true, the pattern \"``**``\" will match any files and zero " "or more directories, subdirectories and symbolic links to directories. If " @@ -130,7 +132,7 @@ msgstr "" "diretórios. Se o padrão for seguido por um :data:`os.sep` ou :data:`os." "altsep`, então os arquivos não irão corresponder." -#: ../../library/glob.rst:69 +#: ../../library/glob.rst:73 msgid "" "If *include_hidden* is true, \"``**``\" pattern will match hidden " "directories." @@ -138,7 +140,7 @@ msgstr "" "Se *include_hidden* for verdadeiro, o padrão \"``**``\" corresponderá aos " "diretórios ocultos." -#: ../../library/glob.rst:71 ../../library/glob.rst:98 +#: ../../library/glob.rst:75 ../../library/glob.rst:102 msgid "" "Raises an :ref:`auditing event ` ``glob.glob`` with arguments " "``pathname``, ``recursive``." @@ -146,7 +148,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``glob.glob`` com os " "argumentos ``pathname``, ``recursive``." -#: ../../library/glob.rst:72 ../../library/glob.rst:99 +#: ../../library/glob.rst:76 ../../library/glob.rst:103 msgid "" "Raises an :ref:`auditing event ` ``glob.glob/2`` with arguments " "``pathname``, ``recursive``, ``root_dir``, ``dir_fd``." @@ -154,7 +156,7 @@ msgstr "" "Levanta um :ref:`evento de auditoria ` ``glob.glob/2`` com os " "argumentos ``pathname``, ``recursive``, ``root_dir``, ``dir_fd``." -#: ../../library/glob.rst:75 +#: ../../library/glob.rst:79 msgid "" "Using the \"``**``\" pattern in large directory trees may consume an " "inordinate amount of time." @@ -162,7 +164,7 @@ msgstr "" "Usar o padrão \"``**``\" em grandes árvores de diretório pode consumir uma " "quantidade excessiva de tempo." -#: ../../library/glob.rst:79 ../../library/glob.rst:102 +#: ../../library/glob.rst:83 ../../library/glob.rst:106 msgid "" "This function may return duplicate path names if *pathname* contains " "multiple \"``**``\" patterns and *recursive* is true." @@ -170,19 +172,19 @@ msgstr "" "Esta função pode retornar nomes de caminhos duplicados se *pathname* " "contiver vários padrões \"``**``\" e *recursive* for verdadeiro." -#: ../../library/glob.rst:82 ../../library/glob.rst:105 +#: ../../library/glob.rst:86 ../../library/glob.rst:109 msgid "Support for recursive globs using \"``**``\"." msgstr "Suporte a globs recursivos usando \"``**``\"." -#: ../../library/glob.rst:85 ../../library/glob.rst:108 +#: ../../library/glob.rst:89 ../../library/glob.rst:112 msgid "Added the *root_dir* and *dir_fd* parameters." msgstr "Adicionados os parâmetros *root_dir* e *dir_fd*." -#: ../../library/glob.rst:88 ../../library/glob.rst:111 +#: ../../library/glob.rst:92 ../../library/glob.rst:115 msgid "Added the *include_hidden* parameter." msgstr "Adicionado o parâmetro *include_hidden*." -#: ../../library/glob.rst:95 +#: ../../library/glob.rst:99 msgid "" "Return an :term:`iterator` which yields the same values as :func:`glob` " "without actually storing them all simultaneously." @@ -190,7 +192,7 @@ msgstr "" "Retorna um :term:`iterador ` que produz os mesmos valores que :" "func:`glob` sem realmente armazená-los todos simultaneamente." -#: ../../library/glob.rst:117 +#: ../../library/glob.rst:121 msgid "" "Escape all special characters (``'?'``, ``'*'`` and ``'['``). This is useful " "if you want to match an arbitrary literal string that may have special " @@ -204,7 +206,7 @@ msgstr "" "compartilhamento de unidade/UNC não têm escape, por exemplo, no Windows " "``escape('//?/c:/Quo vadis?.txt')`` retorna ``'//?/c:/Quo vadis[?].txt'``." -#: ../../library/glob.rst:128 +#: ../../library/glob.rst:132 msgid "" "Convert the given path specification to a regular expression for use with :" "func:`re.match`. The path specification can contain shell-style wildcards." @@ -213,11 +215,11 @@ msgstr "" "com :func:`re.match`. A especificação de caminho pode conter curingas no " "estilo shell." -#: ../../library/glob.rst:131 +#: ../../library/glob.rst:135 msgid "For example:" msgstr "Por exemplo:" -#: ../../library/glob.rst:142 +#: ../../library/glob.rst:146 msgid "" "Path separators and segments are meaningful to this function, unlike :func:" "`fnmatch.translate`. By default wildcards do not match path separators, and " @@ -228,7 +230,7 @@ msgstr "" "correspondem a separadores de caminho, e segmentos de padrão ``*`` " "correspondem precisamente a um segmento de caminho." -#: ../../library/glob.rst:146 +#: ../../library/glob.rst:150 msgid "" "If *recursive* is true, the pattern segment \"``**``\" will match any number " "of path segments." @@ -236,7 +238,7 @@ msgstr "" "Se *recursive* for verdadeiro, o segmento de padrão \"``**``\" corresponderá " "a qualquer número de segmentos de caminho." -#: ../../library/glob.rst:149 +#: ../../library/glob.rst:153 msgid "" "If *include_hidden* is true, wildcards can match path segments that start " "with a dot (``.``)." @@ -244,7 +246,7 @@ msgstr "" "Se *include_hidden* for verdadeiro, os curingas poderão corresponder a " "segmentos de caminho que começam com um ponto (``.``)." -#: ../../library/glob.rst:152 +#: ../../library/glob.rst:156 msgid "" "A sequence of path separators may be supplied to the *seps* argument. If not " "given, :data:`os.sep` and :data:`~os.altsep` (if available) are used." @@ -253,7 +255,7 @@ msgstr "" "*seps*. Se não for fornecido, :data:`os.sep` e :data:`~os.altsep` (se " "disponível) são usados." -#: ../../library/glob.rst:157 +#: ../../library/glob.rst:161 msgid "" ":meth:`pathlib.PurePath.full_match` and :meth:`pathlib.Path.glob` methods, " "which call this function to implement pattern matching and globbing." @@ -262,11 +264,11 @@ msgstr "" "que chamam esta função para implementar correspondência de padrões e " "globbing." -#: ../../library/glob.rst:165 +#: ../../library/glob.rst:169 msgid "Examples" msgstr "Exemplos" -#: ../../library/glob.rst:167 +#: ../../library/glob.rst:171 msgid "" "Consider a directory containing the following files: :file:`1.gif`, :file:`2." "txt`, :file:`card.gif` and a subdirectory :file:`sub` which contains only " @@ -278,7 +280,33 @@ 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:185 +#: ../../library/glob.rst:177 +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:189 msgid "" "If the directory contains files starting with ``.`` they won't be matched by " "default. For example, consider a directory containing :file:`card.gif` and :" @@ -288,14 +316,28 @@ msgstr "" "correspondidos por padrão. Por exemplo, considere um diretório contendo :" "file:`card.gif` e :file:`.card.gif` ::" -#: ../../library/glob.rst:196 +#: ../../library/glob.rst:193 +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:200 msgid "" "The :mod:`fnmatch` module offers shell-style filename (not path) expansion." msgstr "" "O módulo :mod:`fnmatch` oferece expansão de nome de arquivo (não caminho) no " "estilo shell." -#: ../../library/glob.rst:199 +#: ../../library/glob.rst:203 msgid "The :mod:`pathlib` module offers high-level path objects." msgstr "O módulo :mod:`pathlib` oferece objetos de caminho de alto nível." @@ -311,7 +353,7 @@ msgstr "expansão de nome de arquivo" msgid "* (asterisk)" msgstr "* (asterisco)" -#: ../../library/glob.rst:13 ../../library/glob.rst:61 +#: ../../library/glob.rst:13 ../../library/glob.rst:65 msgid "in glob-style wildcards" msgstr "caracteres curingas no estilo blog" @@ -335,6 +377,6 @@ msgstr "- (menos)" msgid ". (dot)" msgstr ". (ponto)" -#: ../../library/glob.rst:61 +#: ../../library/glob.rst:65 msgid "**" msgstr "**" diff --git a/library/graphlib.po b/library/graphlib.po index 6dd7f3dbe..1f6ed4096 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..ef2eb33e7 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..abf928407 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 +# python-doc bot, 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-10-05 14:53+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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:`objeto arquivo`." #: ../../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)compactação do gzip seja um gargalo, o pacote `python-isal`_ " +"acelera a (des)compactaçã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..b8c6db686 100644 --- a/library/hashlib.po +++ b/library/hashlib.po @@ -1,36 +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 -# Raphael Mendonça, 2021 -# i17obot , 2021 -# Marco Rougeth , 2022 -# Claudio Rogerio Carvalho Filho , 2023 -# Vinicius Gubiani Ferreira , 2023 +# python-doc bot, 2025 +# 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-10-03 14:59+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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 +34,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 +69,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 similares ` " +"(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 +98,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 +148,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 +265,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:280 +#: ../../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: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 non-blocking " +"mode. Previously, spurious null bytes were added to the digest." msgstr "" +"Agora levanta uma :exc:`BlockingIOError` se o arquivo for aberto em modo não-" +"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 +474,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 +496,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 +510,208 @@ 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 similares `. 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 "" +"Os objetos hash deste módulo seguem a API dos objetos :mod:`hashlib` da " +"biblioteca padrão." -#: ../../library/hashlib.rst:392 +#: ../../library/hashlib.rst:397 msgid "Creating hash objects" -msgstr "" +msgstr "Criando objetos hash" -#: ../../library/hashlib.rst:394 +#: ../../library/hashlib.rst:399 msgid "New hash objects are created by calling constructor functions:" -msgstr "" +msgstr "Novos objetos hash são criados chamando funções construtoras:" -#: ../../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 "" +"Essas funções retornam os objetos hash correspondentes para calcular BLAKE2b " +"ou BLAKE2s. Opcionalmente, elas aceitam estes parâmetros gerais:" -#: ../../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 "" +"*data*: pedaço inicial de dados para hash, que deve ser :term:`objeto bytes " +"ou similar`. Pode ser passado apenas como argumento posicional." -#: ../../library/hashlib.rst:414 +#: ../../library/hashlib.rst:419 msgid "*digest_size*: size of output digest in bytes." -msgstr "" +msgstr "*digest_size*: tamanho do resumo de saída em bytes." -#: ../../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 "" +"*key*: chave para hash com chave (até 64 bytes para BLAKE2b, até 32 bytes " +"para BLAKE2s)." -#: ../../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 "" +"*salt*: sal para hash aleatório (até 16 bytes para BLAKE2b, até 8 bytes para " +"BLAKE2s)." -#: ../../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 "" +"*person*: string de personalização (até 16 bytes para BLAKE2b, até 8 bytes " +"para BLAKE2s)." -#: ../../library/hashlib.rst:425 +#: ../../library/hashlib.rst:430 msgid "The following table shows limits for general parameters (in bytes):" -msgstr "" +msgstr "A tabela a seguir mostra os limites para parâmetros gerais (em bytes):" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "Hash" -msgstr "" +msgstr "Hash" -#: ../../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 "" +msgstr "len(key)" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "len(salt)" -msgstr "" +msgstr "len(salt)" -#: ../../library/hashlib.rst:428 +#: ../../library/hashlib.rst:433 msgid "len(person)" -msgstr "" +msgstr "len(person)" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "BLAKE2b" -msgstr "" +msgstr "BLAKE2b" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "64" -msgstr "" +msgstr "64" -#: ../../library/hashlib.rst:430 +#: ../../library/hashlib.rst:435 msgid "16" -msgstr "" +msgstr "16" -#: ../../library/hashlib.rst:431 +#: ../../library/hashlib.rst:436 msgid "BLAKE2s" -msgstr "" +msgstr "BLAKE2s" -#: ../../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 +721,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 +817,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 +956,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 +976,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 +997,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 +1090,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 +1215,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..27914c120 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 +# python-doc bot, 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-11-07 15:30+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: pt_BR\n" "Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" @@ -106,10 +105,14 @@ msgid "The following functions are provided:" msgstr "As seguintes funções são fornecidas:" #: ../../library/heapq.rst:47 +msgid "Transform list *x* into a heap, in-place, in linear time." +msgstr "Transforma a lista *x* em um heap, no local, em tempo linear." + +#: ../../library/heapq.rst:52 msgid "Push the value *item* onto the *heap*, maintaining the heap invariant." msgstr "Coloca o valor *item* no *heap*, mantendo o invariante de heap." -#: ../../library/heapq.rst:52 +#: ../../library/heapq.rst:57 msgid "" "Pop and return the smallest item from the *heap*, maintaining the heap " "invariant. If the heap is empty, :exc:`IndexError` is raised. To access " @@ -119,7 +122,7 @@ msgstr "" "heap estiver vazio, a exceção :exc:`IndexError` será levantada. Para acessar " "o menor item sem retirá-lo, use ``heap[0]``." -#: ../../library/heapq.rst:59 +#: ../../library/heapq.rst:64 msgid "" "Push *item* on the heap, then pop and return the smallest item from the " "*heap*. The combined action runs more efficiently than :func:`heappush` " @@ -129,10 +132,6 @@ msgstr "" "ação combinada é executada com mais eficiência do que :func:`heappush` " "seguida por uma chamada separada para :func:`heappop`." -#: ../../library/heapq.rst:66 -msgid "Transform list *x* into a heap, in-place, in linear time." -msgstr "Transforma a lista *x* em um heap, no local, em tempo linear." - #: ../../library/heapq.rst:71 msgid "" "Pop and return the smallest item from the *heap*, and also push the new " @@ -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..633cef6c4 100644 --- a/library/hmac.po +++ b/library/hmac.po @@ -1,42 +1,50 @@ # SOME DESCRIPTIVE TITLE. -# Copyright (C) 2001-2024, Python Software 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 +# python-doc bot, 2025 +# 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-09-17 03:50+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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`" msgstr "**Código-fonte:** :source:`Lib/hmac.py`" #: ../../library/hmac.rst:14 -msgid "This module implements the HMAC algorithm as described by :rfc:`2104`." +msgid "" +"This module implements the HMAC algorithm as described by :rfc:`2104`. The " +"interface allows to use any hash function with a *fixed* digest size. In " +"particular, extendable output functions such as SHAKE-128 or SHAKE-256 " +"cannot be used with HMAC." msgstr "" +"Este módulo implementa o algoritmo HMAC conforme descrito por :rfc:`2104`. A " +"interface permite o uso de qualquer função hash com um tamanho de resumo " +"*fixo*. Em particular, funções de saída extensíveis como SHAKE-128 ou " +"SHAKE-256 não podem ser usadas com HMAC." -#: ../../library/hmac.rst:19 +#: ../../library/hmac.rst:22 msgid "" "Return a new hmac object. *key* is a bytes or bytearray object giving the " "secret key. If *msg* is present, the method call ``update(msg)`` is made. " @@ -44,21 +52,31 @@ 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 +#: ../../library/hmac.rst:28 msgid "" "Parameter *key* can be a bytes or bytearray object. Parameter *msg* can be " "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 +#: ../../library/hmac.rst:33 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 +#: ../../library/hmac.rst:40 msgid "" "Return digest of *msg* for given secret *key* and *digest*. The function is " "equivalent to ``HMAC(key, msg, digest).digest()``, but uses an optimized C " @@ -66,94 +84,129 @@ 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 +#: ../../library/hmac.rst:46 msgid "" "CPython implementation detail, the optimized C implementation is only used " "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 +#: ../../library/hmac.rst:55 msgid "An HMAC object has the following methods:" -msgstr "" +msgstr "Um objeto HMAC tem os seguintes métodos:" -#: ../../library/hmac.rst:54 +#: ../../library/hmac.rst:59 msgid "" "Update the hmac object with *msg*. 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 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 +#: ../../library/hmac.rst:63 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 +#: ../../library/hmac.rst:69 msgid "" "Return the digest of the bytes passed to the :meth:`update` method so far. " "This bytes object will be the same length as the *digest_size* of the digest " "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 +#: ../../library/hmac.rst:76 msgid "" "When comparing the output of :meth:`digest` to an externally supplied digest " "during a verification routine, it is recommended to use the :func:" "`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 +#: ../../library/hmac.rst:84 msgid "" "Like :meth:`digest` except the digest is returned as a string twice the " "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 +#: ../../library/hmac.rst:90 msgid "" "When comparing the output of :meth:`hexdigest` to an externally supplied " "digest during a verification routine, it is recommended to use the :func:" "`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 +#: ../../library/hmac.rst:98 msgid "" "Return a copy (\"clone\") of the hmac object. This can be used to " "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 +#: ../../library/hmac.rst:102 msgid "A hash object has the following attributes:" -msgstr "" +msgstr "Um objeto hash tem os seguintes atributos:" -#: ../../library/hmac.rst:101 +#: ../../library/hmac.rst:106 msgid "The size of the resulting HMAC digest in bytes." -msgstr "" +msgstr "O tamanho do resumo HMAC resultante em bytes." -#: ../../library/hmac.rst:105 +#: ../../library/hmac.rst:110 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 +#: ../../library/hmac.rst:116 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 +#: ../../library/hmac.rst:121 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 +#: ../../library/hmac.rst:125 msgid "This module also provides the following helper function:" msgstr "Este módulo também fornece a seguinte função auxiliar:" -#: ../../library/hmac.rst:124 +#: ../../library/hmac.rst:129 msgid "" "Return ``a == b``. This function uses an approach designed to prevent " "timing analysis by avoiding content-based short circuiting behaviour, making " @@ -161,23 +214,32 @@ 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 +#: ../../library/hmac.rst:137 msgid "" "If *a* and *b* are of different lengths, or if an error occurs, a timing " "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 +#: ../../library/hmac.rst:145 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 +#: ../../library/hmac.rst:151 msgid "Module :mod:`hashlib`" msgstr "Módulo :mod:`hashlib`" -#: ../../library/hmac.rst:147 +#: ../../library/hmac.rst:152 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..77c78f34f 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 +# python-doc bot, 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-09-15 15:19+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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..146c493bb 100644 --- a/library/html.parser.po +++ b/library/html.parser.po @@ -1,32 +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: -# Raphael Mendonça, 2021 -# Rafael Fontenelle , 2024 +# python-doc bot, 2025 +# 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-11-03 15:10+0000\n" +"PO-Revision-Date: 2025-09-15 01:04+0000\n" +"Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/pt_BR/)\n" +"Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 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/html.parser.rst:2 msgid ":mod:`!html.parser` --- Simple HTML and XHTML parser" -msgstr "" +msgstr ":mod:`!html.parser` --- Analisador simples de HTML e XHTML" #: ../../library/html.parser.rst:7 msgid "**Source code:** :source:`Lib/html/parser.py`" @@ -38,112 +38,230 @@ msgid "" "for parsing text files formatted in HTML (HyperText Mark-up Language) and " "XHTML." msgstr "" +"Este módulo define uma classe :class:`HTMLParser` que serve como base para " +"analisar arquivos de texto formatados em HTML (HyperText Markup Language) e " +"XHTML." #: ../../library/html.parser.rst:20 msgid "Create a parser instance able to parse invalid markup." msgstr "" +"Cria uma instância de analisador sintático capaz de analisar marcação " +"inválida." #: ../../library/html.parser.rst:22 msgid "" -"If *convert_charrefs* is ``True`` (the default), all character references " -"(except the ones in ``script``/``style`` elements) are automatically " -"converted to the corresponding Unicode characters." +"If *convert_charrefs* is true (the default), all character references " +"(except the ones in elements like ``script`` and ``style``) are " +"automatically converted to the corresponding Unicode characters." msgstr "" +"Se *convert_charrefs* for verdadeiro (o padrão), todas as referências de " +"caracteres (exceto as de elementos como ``script`` e ``style``) serão " +"convertidas automaticamente para os caracteres Unicode correspondentes." #: ../../library/html.parser.rst:26 msgid "" +"If *scripting* is false (the default), the content of the ``noscript`` " +"element is parsed normally; if it's true, it's returned as is without being " +"parsed." +msgstr "" +"Se *scripting* for falso (o padrão), o conteúdo do elemento ``noscript`` " +"será analisado normalmente; se for verdadeiro, será retornado como está, sem " +"ser analisado." + +#: ../../library/html.parser.rst:30 +msgid "" "An :class:`.HTMLParser` instance is fed HTML data and calls handler methods " "when start tags, end tags, text, comments, and other markup elements are " "encountered. The user should subclass :class:`.HTMLParser` and override its " "methods to implement the desired behavior." msgstr "" +"Uma instância de :class:`.HTMLParser` recebe dados HTML e chama métodos de " +"tratamento quando encontra tags de abertura, tags de fechamento, texto, " +"comentários e outros elementos de marcação. O usuário deve criar uma " +"subclasse de :class:`.HTMLParser` e substituir seus métodos para implementar " +"o comportamento desejado." -#: ../../library/html.parser.rst:31 +#: ../../library/html.parser.rst:35 msgid "" "This parser does not check that end tags match start tags or call the end-" "tag handler for elements which are closed implicitly by closing an outer " "element." msgstr "" +"Este analisador sintático não verifica se as tags de fechamento correspondem " +"às tags de abertura nem chama o manipulador de tags de fechamento para " +"elementos que são fechados implicitamente pelo fechamento de um elemento " +"externo." -#: ../../library/html.parser.rst:34 +#: ../../library/html.parser.rst:38 msgid "*convert_charrefs* keyword argument added." -msgstr "" +msgstr "Adicionado o argumento nomeado *convert_charrefs*." -#: ../../library/html.parser.rst:37 +#: ../../library/html.parser.rst:41 msgid "The default value for argument *convert_charrefs* is now ``True``." -msgstr "" +msgstr "O valor padrão para o argumento *convert_charrefs* agora é ``True``." + +#: ../../library/html.parser.rst:44 +msgid "Added the *scripting* parameter." +msgstr "Adicionado o parâmetro *scripting*." -#: ../../library/html.parser.rst:42 +#: ../../library/html.parser.rst:49 msgid "Example HTML Parser Application" -msgstr "" +msgstr "Exemplo de aplicação para análise de HTML" -#: ../../library/html.parser.rst:44 +#: ../../library/html.parser.rst:51 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::" -msgstr "" - -#: ../../library/html.parser.rst:64 +"encountered:" +msgstr "" +"Como exemplo básico, abaixo está um analisador HTML simples que usa a " +"classe :class:`HTMLParser` para exibir as tags de abertura, tags de " +"fechamento e dados à medida que são encontrados:" + +#: ../../library/html.parser.rst:55 +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 "" +"from html.parser import HTMLParser\n" +"\n" +"class MyHTMLParser(HTMLParser):\n" +" def handle_starttag(self, tag, attrs):\n" +" print(\"Encontrada a tag de abertura :\", tag)\n" +"\n" +" def handle_endtag(self, tag):\n" +" print(\"Encontrada a tag de fechamento:\", tag)\n" +"\n" +" def handle_data(self, data):\n" +" print(\"Encontrados alguns dados :\", data)\n" +"\n" +"parser = MyHTMLParser()\n" +"parser.feed('Teste'\n" +" '

Me analise!

')" + +#: ../../library/html.parser.rst:73 msgid "The output will then be:" -msgstr "" - -#: ../../library/html.parser.rst:83 +msgstr "A saída então será:" + +#: ../../library/html.parser.rst:75 +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 "" +"Encontrada a tag de abertura : html\n" +"Encontrada a tag de abertura : head\n" +"Encontrada a tag de abertura : title\n" +"Encontrados alguns dados : Teste\n" +"Encontrada a tag de fechamento: title\n" +"Encontrada a tag de fechamento: head\n" +"Encontrada a tag de abertura : body\n" +"Encontrada a tag de abertura : h1\n" +"Encontrados alguns dados : Me analise!\n" +"Encontrada a tag de fechamento: h1\n" +"Encontrada a tag de fechamento: body\n" +"Encontrada a tag de fechamento: html" + +#: ../../library/html.parser.rst:92 msgid ":class:`.HTMLParser` Methods" -msgstr "" +msgstr "Métodos :class:`.HTMLParser`" -#: ../../library/html.parser.rst:85 +#: ../../library/html.parser.rst:94 msgid ":class:`HTMLParser` instances have the following methods:" -msgstr "" +msgstr "Instâncias de :class:`HTMLParser` têm os seguintes métodos:" -#: ../../library/html.parser.rst:90 +#: ../../library/html.parser.rst:99 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 "" +"Fornece algum texto ao analisador. Ele será processado na medida em que " +"consistir em elementos completos; dados incompletos serão armazenados em " +"buffer até que mais dados sejam fornecidos ou que o método :meth:`close` " +"seja chamado. Os dados devem ser do tipo :class:`str`." -#: ../../library/html.parser.rst:97 +#: ../../library/html.parser.rst:106 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 " "additional processing at the end of the input, but the redefined version " "should always call the :class:`HTMLParser` base class method :meth:`close`." msgstr "" +"Força o processamento de todos os dados em buffer como se fossem seguidos " +"por uma marca de fim de arquivo. Este método pode ser redefinido por uma " +"classe derivada para definir processamento adicional no final da entrada, " +"mas a versão redefinida deve sempre chamar o método :meth:`close` da classe " +"base :class:`HTMLParser`." -#: ../../library/html.parser.rst:105 +#: ../../library/html.parser.rst:114 msgid "" "Reset the instance. Loses all unprocessed data. This is called implicitly " "at instantiation time." msgstr "" +"Reinicializa a instância. Perde todos os dados não processados. Este método " +"é chamado implicitamente no momento da instanciação." -#: ../../library/html.parser.rst:111 +#: ../../library/html.parser.rst:120 msgid "Return current line number and offset." -msgstr "" +msgstr "Retorna o número da linha atual e o deslocamento." -#: ../../library/html.parser.rst:116 +#: ../../library/html.parser.rst:125 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 " "with HTML \"as deployed\" or for re-generating input with minimal changes " "(whitespace between attributes can be preserved, etc.)." msgstr "" +"Retorna o texto da tag de abertura aberta mais recentemente. Normalmente, " +"isso não é necessário para processamento estruturado, mas pode ser útil ao " +"lidar com HTML \"como implantado\" ou para regenerar a entrada com " +"alterações mínimas (o espaço em branco entre os atributos pode ser " +"preservado, etc.)." -#: ../../library/html.parser.rst:122 +#: ../../library/html.parser.rst:131 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 " "class implementations do nothing (except for :meth:`~HTMLParser." "handle_startendtag`):" msgstr "" +"Os seguintes métodos são chamados quando elementos de dados ou de marcação " +"são encontrados e devem ser sobrescritos em uma subclasse. As implementações " +"da classe base não fazem nada (exceto por :meth:`~HTMLParser." +"handle_startendtag`):" -#: ../../library/html.parser.rst:129 +#: ../../library/html.parser.rst:138 msgid "" "This method is called to handle the start tag of an element (e.g. ``
``)." msgstr "" +"Este método é chamado para manipular a tag de abertura de um elemento (por " +"exemplo, ``
``)." -#: ../../library/html.parser.rst:131 +#: ../../library/html.parser.rst:140 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 " @@ -151,30 +269,43 @@ msgid "" "translated to lower case, and quotes in the *value* have been removed, and " "character and entity references have been replaced." msgstr "" +"O argumento *tag* é o nome da tag convertido para minúsculas. O argumento " +"*attrs* é uma lista de pares ``(nome, valor)`` contendo os atributos " +"encontrados dentro dos colchetes ``<>`` da tag. O *nome* será traduzido para " +"minúsculas, as aspas no *valor* foram removidas e as referências a " +"caracteres e entidades foram substituídas." -#: ../../library/html.parser.rst:137 +#: ../../library/html.parser.rst:146 msgid "" "For instance, for the tag ````, this method " "would be called as ``handle_starttag('a', [('href', 'https://www.cwi." "nl/')])``." msgstr "" +"Por exemplo, para a tag ````, este método " +"seria chamado como ``handle_starttag('a', [('href', 'https://www.cwi." +"nl/')])``." -#: ../../library/html.parser.rst:140 +#: ../../library/html.parser.rst:149 msgid "" "All entity references from :mod:`html.entities` are replaced in the " "attribute values." msgstr "" +"Todas as referências de entidade de :mod:`html.entities` são substituídas " +"nos valores dos atributos." -#: ../../library/html.parser.rst:146 +#: ../../library/html.parser.rst:155 msgid "" "This method is called to handle the end tag of an element (e.g. ``
``)." msgstr "" +"Este método é chamado para manipular a tag de fechamento de um elemento (por " +"exemplo, ``
``)." -#: ../../library/html.parser.rst:148 +#: ../../library/html.parser.rst:157 msgid "The *tag* argument is the name of the tag converted to lower case." msgstr "" +"O argumento *tag* é o nome da etiqueta convertido para letras minúsculas." -#: ../../library/html.parser.rst:153 +#: ../../library/html.parser.rst:162 msgid "" "Similar to :meth:`handle_starttag`, but called when the parser encounters an " "XHTML-style empty tag (````). This method may be overridden by " @@ -182,62 +313,90 @@ msgid "" "implementation simply calls :meth:`handle_starttag` and :meth:" "`handle_endtag`." msgstr "" +"Similar a :meth:`handle_starttag`, mas chamado quando o analisador sintático " +"encontra uma tag vazia no estilo XHTML (````). Este método pode " +"ser substituído por subclasses que requerem essa informação lexical " +"específica; a implementação padrão simplesmente chama :meth:" +"`handle_starttag` e :meth:`handle_endtag`." -#: ../../library/html.parser.rst:161 +#: ../../library/html.parser.rst:170 msgid "" "This method is called to process arbitrary data (e.g. text nodes and the " -"content of ```` and ````)." +"content of elements like ``script`` and ``style``)." msgstr "" +"Este método é chamado para processar dados arbitrários (por exemplo, nós de " +"texto e o conteúdo de elementos como ``script`` e ``style``)." -#: ../../library/html.parser.rst:167 +#: ../../library/html.parser.rst:176 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``." +"``'gt'``). This method is only called if *convert_charrefs* is false." msgstr "" +"Este método é chamado para processar uma referência de caractere nomeada no " +"formato ``&name;`` (por exemplo, ``>``), onde *name* é uma referência de " +"entidade genérica (por exemplo, ``'gt'``). Este método só é chamado se " +"*convert_charrefs* for falso." -#: ../../library/html.parser.rst:175 +#: ../../library/html.parser.rst:184 msgid "" "This method is called to process decimal and hexadecimal numeric character " "references of the form :samp:`&#{NNN};` and :samp:`&#x{NNN};`. For example, " "the decimal equivalent for ``>`` is ``>``, whereas the hexadecimal is " -"``>``; in this case the method will receive ``'62'`` or ``'x3E'``. " -"This method is never called if *convert_charrefs* is ``True``." +"``>``; in this case the method will receive ``'62'`` or ``'x3E'``. This " +"method is only called if *convert_charrefs* is false." msgstr "" +"Este método é chamado para processar referências de caracteres numéricos " +"decimais e hexadecimais no formato :samp:`&#{NNN};` e :samp:`&#x{NNN};`. Por " +"exemplo, o equivalente decimal para ``>`` é ``>``, enquanto o " +"hexadecimal é ``>``; neste caso, o método receberá ``'62'`` ou " +"``'x3E'``. Este método só é chamado se *convert_charrefs* for falso." -#: ../../library/html.parser.rst:184 +#: ../../library/html.parser.rst:193 msgid "" "This method is called when a comment is encountered (e.g. ````)." -#: ../../library/html.parser.rst:186 +#: ../../library/html.parser.rst:195 msgid "" "For example, the comment ```` will cause this method to be " "called with the argument ``' comment '``." msgstr "" +"Por exemplo, o comentário ```` fará com que este método " +"seja chamado com o argumento ``' comentário '``." -#: ../../library/html.parser.rst:189 +#: ../../library/html.parser.rst:198 msgid "" "The content of Internet Explorer conditional comments (condcoms) will also " "be sent to this method, so, for ````, this method will receive ``'[if IE 9]>IE9-specific contentconteúdo específico do IE9``, este método receberá ``'[if IE " +"9]>conteúdo específico do IE9``)." msgstr "" +"Este método é chamado para lidar com uma declaração de doctype HTML (por " +"exemplo, ````)." -#: ../../library/html.parser.rst:199 +#: ../../library/html.parser.rst:208 msgid "" "The *decl* parameter will be the entire contents of the declaration inside " "the ```` markup (e.g. ``'DOCTYPE html'``)." msgstr "" +"O parâmetro *decl* será todo o conteúdo da declaração dentro da marcação " +"```` (por exemplo, ``'DOCTYPE html'``)." -#: ../../library/html.parser.rst:205 +#: ../../library/html.parser.rst:214 msgid "" "Method called when a processing instruction is encountered. The *data* " "parameter will contain the entire processing instruction. For example, for " @@ -245,69 +404,205 @@ msgid "" "called as ``handle_pi(\"proc color='red'\")``. It is intended to be " "overridden by a derived class; the base class implementation does nothing." msgstr "" +"Método chamado quando uma instrução de processamento é encontrada. O " +"parâmetro *data* conterá a instrução de processamento completa. Por exemplo, " +"para a instrução de processamento ````, este método seria " +"chamado como ``handle_pi(\"proc color='red'\")``. Ele foi projetado para ser " +"substituído por uma classe derivada; a implementação da classe base não faz " +"nada." -#: ../../library/html.parser.rst:213 +#: ../../library/html.parser.rst:222 msgid "" "The :class:`HTMLParser` class uses the SGML syntactic rules for processing " "instructions. An XHTML processing instruction using the trailing ``'?'`` " "will cause the ``'?'`` to be included in *data*." msgstr "" +"A classe :class:`HTMLParser` usa as regras sintáticas SGML para processar " +"instruções. Uma instrução de processamento XHTML que usa o caractere ``'?'`` " +"no final fará com que o ``'?'`` seja incluído em *data*." -#: ../../library/html.parser.rst:220 +#: ../../library/html.parser.rst:229 msgid "" "This method is called when an unrecognized declaration is read by the parser." msgstr "" +"Este método é chamado quando uma declaração não reconhecida é lida pelo " +"analisador sintático." -#: ../../library/html.parser.rst:222 +#: ../../library/html.parser.rst:231 msgid "" "The *data* parameter will be the entire contents of the declaration inside " "the ```` markup. It is sometimes useful to be overridden by a " "derived class. The base class implementation does nothing." msgstr "" +"O parâmetro *data* será todo o conteúdo da declaração dentro da marcação ````. Às vezes, é útil que ele seja sobrescrito por uma classe derivada. " +"A implementação da classe base não faz nada." -#: ../../library/html.parser.rst:230 +#: ../../library/html.parser.rst:239 msgid "Examples" msgstr "Exemplos" -#: ../../library/html.parser.rst:232 +#: ../../library/html.parser.rst:241 msgid "" "The following class implements a parser that will be used to illustrate more " -"examples::" +"examples:" +msgstr "" +"A classe a seguir implementa um analisador sintático que será usado para " +"ilustrar mais exemplos:" + +#: ../../library/html.parser.rst:244 +msgid "" +"from html.parser import HTMLParser\n" +"from html.entities import name2codepoint\n" +"\n" +"class MyHTMLParser(HTMLParser):\n" +" def handle_starttag(self, tag, attrs):\n" +" print(\"Start tag:\", tag)\n" +" for attr in attrs:\n" +" print(\" attr:\", attr)\n" +"\n" +" def handle_endtag(self, tag):\n" +" print(\"End tag :\", tag)\n" +"\n" +" def handle_data(self, data):\n" +" print(\"Data :\", data)\n" +"\n" +" def handle_comment(self, data):\n" +" print(\"Comment :\", data)\n" +"\n" +" def handle_entityref(self, name):\n" +" c = chr(name2codepoint[name])\n" +" print(\"Named ent:\", c)\n" +"\n" +" def handle_charref(self, name):\n" +" if name.startswith('x'):\n" +" c = chr(int(name[1:], 16))\n" +" else:\n" +" c = chr(int(name))\n" +" print(\"Num ent :\", c)\n" +"\n" +" def handle_decl(self, data):\n" +" print(\"Decl :\", data)\n" +"\n" +"parser = MyHTMLParser()" +msgstr "" + +#: ../../library/html.parser.rst:280 +msgid "Parsing a doctype:" +msgstr "" + +#: ../../library/html.parser.rst:282 +msgid "" +">>> parser.feed('')\n" +"Decl : DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3." +"org/TR/html4/strict.dtd\"" +msgstr "" + +#: ../../library/html.parser.rst:288 +msgid "Parsing an element with a few attributes and a title:" msgstr "" -#: ../../library/html.parser.rst:269 -msgid "Parsing a doctype::" +#: ../../library/html.parser.rst:290 +msgid "" +">>> parser.feed('\"The')\n" +"Start tag: img\n" +" attr: ('src', 'python-logo.png')\n" +" attr: ('alt', 'The Python logo')\n" +">>>\n" +">>> parser.feed('

Python

')\n" +"Start tag: h1\n" +"Data : Python\n" +"End tag : h1" msgstr "" -#: ../../library/html.parser.rst:275 -msgid "Parsing an element with a few attributes and a title::" +#: ../../library/html.parser.rst:302 +msgid "" +"The content of elements like ``script`` and ``style`` is returned as is, " +"without further parsing:" msgstr "" -#: ../../library/html.parser.rst:287 +#: ../../library/html.parser.rst:305 msgid "" -"The content of ``script`` and ``style`` elements is returned as is, without " -"further parsing::" +">>> parser.feed('