-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathprogramming.po
More file actions
3002 lines (2630 loc) · 129 KB
/
programming.po
File metadata and controls
3002 lines (2630 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2025, Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
# Translators:
# python-doc bot, 2025
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.9\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-09-22 21:56+0000\n"
"PO-Revision-Date: 2025-09-22 17:54+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"
#: ../../faq/programming.rst:5
msgid "Programming FAQ"
msgstr "FAQ sobre programação"
#: ../../faq/programming.rst:8
msgid "Contents"
msgstr "Conteúdo"
#: ../../faq/programming.rst:12
msgid "General Questions"
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 possua pontos de interrupção "
"(*breakpoints*), single-stepping, etc.?"
#: ../../faq/programming.rst:17 ../../faq/programming.rst:57
msgid "Yes."
msgstr "Sim."
#: ../../faq/programming.rst:19
msgid ""
"Several debuggers for Python are described below, and the built-in function :"
"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 desses pontos."
#: ../../faq/programming.rst:22
msgid ""
"The pdb module is a simple but adequate console-mode debugger for Python. It "
"is part of the standard Python library, and is :mod:`documented in the "
"Library Reference Manual <pdb>`. You can also write your own debugger by "
"using the code for pdb as an example."
msgstr ""
"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 <pdb>`. Você também pode construir do "
"seu próprio depurador usando o código do pdb como um exemplo."
#: ../../faq/programming.rst:27
msgid ""
"The IDLE interactive development environment, which is part of the standard "
"Python distribution (normally available as Tools/scripts/idle), includes a "
"graphical debugger."
msgstr ""
"O Ambiente de Desenvolvimento Interativo IDLE, que faz parte da distribuição "
"padrão do Python (normalmente disponível em Tools/scripts/idle), inclui um "
"depurador gráfico."
#: ../../faq/programming.rst:31
msgid ""
"PythonWin is a Python IDE that includes a GUI debugger based on pdb. The "
"PythonWin debugger colors breakpoints and has quite a few cool features such "
"as debugging non-PythonWin programs. PythonWin is available as part of "
"`pywin32 <https://github.com/mhammond/pywin32>`_ project and as a part of "
"the `ActivePython <https://www.activestate.com/products/python/>`_ "
"distribution."
msgstr ""
"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 "
"<https://github.com/mhammond/pywin32>`_ e como parte da distribuição "
"`ActivePython <https://www.activestate.com/products/python/>`_."
#: ../../faq/programming.rst:38
msgid ""
"`Eric <http://eric-ide.python-projects.org/>`_ is an IDE built on PyQt and "
"the Scintilla editing component."
msgstr ""
"O `Eric <http://eric-ide.python-projects.org/>`_ é uma IDE construída com o "
"PyQt e fazendo uso do componente de edição Scintilla."
#: ../../faq/programming.rst:41
msgid ""
"`trepan3k <https://github.com/rocky/python3-trepan/>`_ is a gdb-like "
"debugger."
msgstr ""
"`trepan3k <https://github.com/rocky/python3-trepan/>`_ é um depurador "
"similar ao gdb."
#: ../../faq/programming.rst:43
msgid ""
"`Visual Studio Code <https://code.visualstudio.com/>`_ is an IDE with "
"debugging tools that integrates with version-control software."
msgstr ""
"`Visual Studio Code <https://code.visualstudio.com/>`_ é uma IDE com "
"ferramentas de depuração integrada com softwares de controle de versão."
#: ../../faq/programming.rst:46
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 inclui "
"depuradores gráficos. Dentre tantas temos:"
#: ../../faq/programming.rst:49
msgid "`Wing IDE <https://wingware.com/>`_"
msgstr "`Wing IDE <https://wingware.com/>`_"
#: ../../faq/programming.rst:50
msgid "`Komodo IDE <https://www.activestate.com/products/komodo-ide/>`_"
msgstr "`Komodo IDE <https://www.activestate.com/products/komodo-ide/>`_"
#: ../../faq/programming.rst:51
msgid "`PyCharm <https://www.jetbrains.com/pycharm/>`_"
msgstr "`PyCharm <https://www.jetbrains.com/pycharm/>`_"
#: ../../faq/programming.rst:55
msgid "Are there tools to help find bugs or perform static analysis?"
msgstr ""
"Existem ferramentas para ajudar a encontrar bugs ou fazer análise estática "
"de desempenho?"
#: ../../faq/programming.rst:59
msgid ""
"`Pylint <https://www.pylint.org/>`_ and `Pyflakes <https://github.com/PyCQA/"
"pyflakes>`_ do basic checking that will help you catch bugs sooner."
msgstr ""
"`Pylint <https://www.pylint.org/>`_ e `Pyflakes <https://github.com/PyCQA/"
"pyflakes>`_ fazem análises básicas que irão ajudar você a capturar os bugs "
"rapidamente."
#: ../../faq/programming.rst:63
msgid ""
"Static type checkers such as `Mypy <http://mypy-lang.org/>`_, `Pyre <https://"
"pyre-check.org/>`_, and `Pytype <https://github.com/google/pytype>`_ can "
"check type hints in Python source code."
msgstr ""
"Verificadores de tipo estático como `Mypy <http://mypy-lang.org/>`_, `Pyre "
"<https://pyre-check.org/>`_, e `Pytype <https://github.com/google/pytype>`_ "
"podem verificar as dicas de tipo no código-fonte Python."
#: ../../faq/programming.rst:72
msgid "How can I create a stand-alone binary from a Python script?"
msgstr "Como posso criar um binário independente a partir de um script Python?"
#: ../../faq/programming.rst:74
msgid ""
"You don't need the ability to compile Python to C code if all you want is a "
"stand-alone program that users can download and run without having to "
"install the Python distribution first. There are a number of tools that "
"determine the set of modules required by a program and bind these modules "
"together with a Python binary to produce a single executable."
msgstr ""
"Você não precisa possuir a capacidade de compilar o código Python para C se "
"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 ao binário do Python para produzir um único "
"executável."
#: ../../faq/programming.rst:80
msgid ""
"One is to use the freeze tool, which is included in the Python source tree "
"as ``Tools/freeze``. It converts Python byte code to C arrays; with a C "
"compiler you can embed all your modules into a new program, which is then "
"linked with the standard Python modules."
msgstr ""
#: ../../faq/programming.rst:85
msgid ""
"It works by scanning your source recursively for import statements (in both "
"forms) and looking for the modules in the standard Python path as well as in "
"the source directory (for built-in modules). It then turns the bytecode for "
"modules written in Python into C code (array initializers that can be turned "
"into code objects using the marshal module) and creates a custom-made config "
"file that only contains those built-in modules which are actually used in "
"the program. It then compiles the generated C code and links it with the "
"rest of the Python interpreter to form a self-contained binary which acts "
"exactly like your script."
msgstr ""
"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:94
msgid ""
"The following packages can help with the creation of console and GUI "
"executables:"
msgstr ""
"Os pacotes a seguir podem ajudar com a criação dos executáveis do console e "
"da GUI:"
#: ../../faq/programming.rst:97
msgid "`Nuitka <https://nuitka.net/>`_ (Cross-platform)"
msgstr "`Nuitka <https://nuitka.net/>`_ (Multiplataforma)"
#: ../../faq/programming.rst:98
msgid "`PyInstaller <http://www.pyinstaller.org/>`_ (Cross-platform)"
msgstr "`PyInstaller <http://www.pyinstaller.org/>`_ (multiplataforma)"
#: ../../faq/programming.rst:99
msgid ""
"`PyOxidizer <https://pyoxidizer.readthedocs.io/en/stable/>`_ (Cross-platform)"
msgstr ""
"`PyOxidizer <https://pyoxidizer.readthedocs.io/en/stable/>`_ "
"(Multiplataforma)"
#: ../../faq/programming.rst:100
msgid ""
"`cx_Freeze <https://marcelotduarte.github.io/cx_Freeze/>`_ (Cross-platform)"
msgstr ""
"`cx_Freeze <https://marcelotduarte.github.io/cx_Freeze/>`_ (Multiplataforma)"
#: ../../faq/programming.rst:101
msgid "`py2app <https://github.com/ronaldoussoren/py2app>`_ (macOS only)"
msgstr "`py2app <https://github.com/ronaldoussoren/py2app>`_ (somente macOS)"
#: ../../faq/programming.rst:102
msgid "`py2exe <http://www.py2exe.org/>`_ (Windows only)"
msgstr "`py2exe <http://www.py2exe.org/>`_ (somente Windows)"
#: ../../faq/programming.rst:105
msgid "Are there coding standards or a style guide for Python programs?"
msgstr ""
"Existem padrões para a codificação ou um guia de estilo utilizado pela "
"comunidade Python?"
#: ../../faq/programming.rst:107
msgid ""
"Yes. The coding style required for standard library modules is documented "
"as :pep:`8`."
msgstr ""
"Sim. O guia de estilo esperado para módulos e biblioteca padrão possui o "
"nome de PEP8 e você pode acessar a sua documentação em :pep:`8`."
#: ../../faq/programming.rst:112
msgid "Core Language"
msgstr "Núcleo da linguagem"
#: ../../faq/programming.rst:115
msgid "Why am I getting an UnboundLocalError when the variable has a value?"
msgstr ""
"Porque recebo o erro UnboundLocalError quando a variável possui um valor "
"associado?"
#: ../../faq/programming.rst:117
msgid ""
"It can be a surprise to get the UnboundLocalError in previously working code "
"when it is modified by adding an assignment statement somewhere in the body "
"of a function."
msgstr ""
"Talvez você se surpreenda ao receber UnboundLocalError num código que "
"anteriormente funcionava quando este for modificado e adicionando uma "
"declaração de atribuição em algum lugar no corpo de uma função."
#: ../../faq/programming.rst:121
msgid "This code:"
msgstr "Este código:"
#: ../../faq/programming.rst:129
msgid "works, but this code:"
msgstr "funciona, mas este código:"
#: ../../faq/programming.rst:136
msgid "results in an UnboundLocalError:"
msgstr "resultará em um UnboundLocalError:"
#: ../../faq/programming.rst:143
msgid ""
"This is because when you make an assignment to a variable in a scope, that "
"variable becomes local to that scope and shadows any similarly named "
"variable in the outer scope. Since the last statement in foo assigns a new "
"value to ``x``, the compiler recognizes it as a local variable. "
"Consequently when the earlier ``print(x)`` attempts to print the "
"uninitialized local variable and an error results."
msgstr ""
"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:150
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-a "
"como global:"
#: ../../faq/programming.rst:161
msgid ""
"This explicit declaration is required in order to remind you that (unlike "
"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 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:168
msgid ""
"You can do a similar thing in a nested scope using the :keyword:`nonlocal` "
"keyword:"
msgstr ""
"Podemos fazer algo parecido num escopo aninhado usando a palavra reservada :"
"keyword:`nonlocal`:"
#: ../../faq/programming.rst:185
msgid "What are the rules for local and global variables in Python?"
msgstr "Quais são as regras para variáveis locais e globais em Python?"
#: ../../faq/programming.rst:187
msgid ""
"In Python, variables that are only referenced inside a function are "
"implicitly global. If a variable is assigned a value anywhere within the "
"function's body, it's assumed to be a local unless explicitly declared as "
"global."
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 "
"seja local, a menos que seja explicitamente declarada como global."
#: ../../faq/programming.rst:191
msgid ""
"Though a bit surprising at first, a moment's consideration explains this. "
"On one hand, requiring :keyword:`global` for assigned variables provides a "
"bar against unintended side-effects. On the other hand, if ``global`` was "
"required for all global references, you'd be using ``global`` all the time. "
"You'd have to declare as global every reference to a built-in function or to "
"a component of an imported module. This clutter would defeat the usefulness "
"of the ``global`` declaration for identifying side-effects."
msgstr ""
"Embora um pouco surpreendente no início, um momento de consideração explica "
"isso. Por um lado, exigir :keyword:`global` para variáveis atribuídas "
"fornece uma barreira contra efeitos colaterais indesejados. Por outro lado, "
"se ``global`` fosse necessário para todas as referências globais, você "
"estaria usando ``global`` o tempo todo. Você teria que declarar como global "
"todas as referências a uma função embutida ou a um componente de um módulo "
"importado. Essa desordem anularia a utilidade da declaração de ``global`` "
"para identificar efeitos colaterais."
#: ../../faq/programming.rst:201
msgid ""
"Why do lambdas defined in a loop with different values all return the same "
"result?"
msgstr ""
"Por que os lambdas definidos em um laço com valores diferentes retornam o "
"mesmo resultado?"
#: ../../faq/programming.rst:203
msgid ""
"Assume you use a for loop to define a few different lambdas (or even plain "
"functions), e.g.::"
msgstr ""
"Suponha que se utilize um laço `for` para definir algumas funções lambdas "
"(ou mesmo funções simples), por exemplo.::"
#: ../../faq/programming.rst:210
msgid ""
"This gives you a list that contains 5 lambdas that calculate ``x**2``. You "
"might expect that, when called, they would return, respectively, ``0``, "
"``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``. 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:220
msgid ""
"This happens because ``x`` is not local to the lambdas, but is defined in "
"the outer scope, and it is accessed when the lambda is called --- not when "
"it is defined. At the end of the loop, the value of ``x`` is ``4``, so all "
"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 os lambdas, mas é definido no "
"escopo externo, e é acessado quando o lambda for chamado --- não quando é "
"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:230
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, é 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:237
msgid ""
"Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed "
"when the lambda is defined so that it has the same value that ``x`` had at "
"that point in the loop. This means that the value of ``n`` will be ``0`` in "
"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 é 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:248
msgid ""
"Note that this behaviour is not peculiar to lambdas, but applies to regular "
"functions too."
msgstr ""
"Observe que esse comportamento não é peculiar dos lambdas, o mesmo também "
"ocorre com as funções regulares."
#: ../../faq/programming.rst:253
msgid "How do I share global variables across modules?"
msgstr "Como definir variáveis globais dentro de módulos?"
#: ../../faq/programming.rst:255
msgid ""
"The canonical way to share information across modules within a single "
"program is to create a special module (often called config or cfg). Just "
"import the config module in all modules of your application; the module then "
"becomes available as a global name. Because there is only one instance of "
"each module, any changes made to the module object get reflected "
"everywhere. For example:"
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 "
"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:"
#: ../../faq/programming.rst:261
msgid "config.py::"
msgstr "config.py::"
#: ../../faq/programming.rst:265
msgid "mod.py::"
msgstr "mod.py::"
#: ../../faq/programming.rst:270
msgid "main.py::"
msgstr "main.py::"
#: ../../faq/programming.rst:276
msgid ""
"Note that using a module is also the basis for implementing the Singleton "
"design pattern, for the same reason."
msgstr ""
"Observe o uso de um único módulo também é, por definição, a implementação do "
"Design Patterns Singleton!"
#: ../../faq/programming.rst:281
msgid "What are the \"best practices\" for using import in a module?"
msgstr ""
"Quais são as \"melhores práticas\" quando fazemos uso da importação de "
"módulos?"
#: ../../faq/programming.rst:283
msgid ""
"In general, don't use ``from modulename import *``. Doing so clutters the "
"importer's namespace, and makes it much harder for linters to detect "
"undefined names."
msgstr ""
"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:287
msgid ""
"Import modules at the top of a file. Doing so makes it clear what other "
"modules your code requires and avoids questions of whether the module name "
"is in scope. Using one import per line makes it easy to add and delete "
"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 "
"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."
#: ../../faq/programming.rst:292
msgid "It's good practice if you import modules in the following order:"
msgstr "É uma boa prática importar os módulos na seguinte ordem:"
#: ../../faq/programming.rst:294
msgid "standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``"
msgstr ""
"módulos de biblioteca padrão, por exemplo: ``sys``, ``os``, ``getopt``, "
"``re``"
#: ../../faq/programming.rst:295
msgid ""
"third-party library modules (anything installed in Python's site-packages "
"directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc."
msgstr ""
"módulos e biblioteca de terceiros (qualquer instalação feita contida no "
"repositório de códigos na pasta site-packages) - por exemplo mx.DateTime, "
"ZODB, PIL.Image, etc."
#: ../../faq/programming.rst:297
msgid "locally-developed modules"
msgstr "módulos desenvolvidos localmente"
#: ../../faq/programming.rst:299
msgid ""
"It is sometimes necessary to move imports to a function or class to avoid "
"problems with circular imports. Gordon McMillan says:"
msgstr ""
"Às vezes, é necessário transferir as importações para uma função ou classe "
"para evitar problemas com importação circular. Gordon McMillan diz:"
#: ../../faq/programming.rst:302
msgid ""
"Circular imports are fine where both modules use the \"import <module>\" "
"form of import. They fail when the 2nd module wants to grab a name out of "
"the first (\"from module import name\") and the import is at the top level. "
"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 vão bem onde ambos os módulos utilizam a forma de "
"importação \"import <módulo>\". 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 1º módulo está ocupado importando o 2º."
#: ../../faq/programming.rst:308
msgid ""
"In this case, if the second module is only used in one function, then the "
"import can easily be moved into that function. By the time the import is "
"called, the first module will have finished initializing, and the second "
"module can do its import."
msgstr ""
"Nesse caso, se o segundo módulo for usado apenas numa função, a importação "
"pode ser facilmente movida para dentro do escopo dessa função. No momento em "
"que a importação for chamada, o primeiro módulo terá finalizado a "
"inicialização e o segundo módulo poderá ser importado sem maiores "
"complicações."
#: ../../faq/programming.rst:313
msgid ""
"It may also be necessary to move imports out of the top level of code if "
"some of the modules are platform-specific. In that case, it may not even be "
"possible to import all of the modules at the top of the file. In this case, "
"importing the correct modules in the corresponding platform-specific code is "
"a good option."
msgstr ""
"Também poderá ser necessário mover as importações para fora do nível "
"superior do código se alguns dos módulos forem específicos de uma "
"determinada plataforma (SO). Nesse caso, talvez nem seja possível importar "
"todos os módulos na parte superior do arquivo. Nessas situações devemos "
"importar os módulos que são específicos de cada plataforma antes de "
"necessitar utilizar os mesmos."
#: ../../faq/programming.rst:318
msgid ""
"Only move imports into a local scope, such as inside a function definition, "
"if it's necessary to solve a problem such as avoiding a circular import or "
"are trying to reduce the initialization time of a module. This technique is "
"especially helpful if many of the imports are unnecessary depending on how "
"the program executes. You may also want to move imports into a function if "
"the modules are only ever used in that function. Note that loading a module "
"the first time may be expensive because of the one time initialization of "
"the module, but loading a module multiple times is virtually free, costing "
"only a couple of dictionary lookups. Even if the module name has gone out "
"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, 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:331
msgid "Why are default values shared between objects?"
msgstr "Por que os valores padrão são compartilhados entre objetos?"
#: ../../faq/programming.rst:333
msgid ""
"This type of bug commonly bites neophyte programmers. Consider this "
"function::"
msgstr ""
"Este tipo de erro geralmente pega programadores neófitos. Considere esta "
"função::"
#: ../../faq/programming.rst:340
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 ""
"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:344
msgid ""
"It is often expected that a function call creates new objects for default "
"values. This is not what happens. Default values are created exactly once, "
"when the function is defined. If that object is changed, like the "
"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 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:349
msgid ""
"By definition, immutable objects such as numbers, strings, tuples, and "
"``None``, are safe from change. Changes to mutable objects such as "
"dictionaries, lists, and class instances can lead to confusion."
msgstr ""
"Por definição, objetos imutáveis, como números, strings, tuplas e o "
"``None``, estão protegidos de sofrerem alteração. Alterações em objetos "
"mutáveis, como dicionários, listas e instâncias de classe, podem levar à "
"confusão."
#: ../../faq/programming.rst:353
msgid ""
"Because of this feature, it is good programming practice to not use mutable "
"objects as default values. Instead, use ``None`` as the default value and "
"inside the function, check if the parameter is ``None`` and create a new "
"list/dictionary/whatever if it is. For example, don't write::"
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 ou o que quer que seja. Por exemplo, "
"escreva o seguinte código::"
#: ../../faq/programming.rst:361
msgid "but::"
msgstr "mas::"
#: ../../faq/programming.rst:367
msgid ""
"This feature can be useful. When you have a function that's time-consuming "
"to compute, a common technique is to cache the parameters and the resulting "
"value of each call to the function, and return the cached value if the same "
"value is requested again. This is called \"memoizing\", and can be "
"implemented like this::"
msgstr ""
"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:382
msgid ""
"You could use a global variable containing a dictionary instead of the "
"default value; it's a matter of taste."
msgstr ""
"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:387
msgid ""
"How can I pass optional or keyword parameters from one function to another?"
msgstr ""
"Como passo parâmetros opcionais ou parâmetros nomeados de uma função para "
"outra?"
#: ../../faq/programming.rst:389
msgid ""
"Collect the arguments using the ``*`` and ``**`` specifiers in the "
"function's parameter list; this gives you the positional arguments as a "
"tuple and the keyword arguments as a dictionary. You can then pass these "
"arguments when calling another function by using ``*`` and ``**``::"
msgstr ""
"Colete os argumentos usando os especificadores ``*`` ou ``**`` na lista de "
"parâmetros da função. Isso faz com que os argumentos posicionais como tupla "
"e os argumentos nomeados sejam passados como um dicionário. Você pode, "
"também, passar esses argumentos ao invocar outra função usando ``*`` e "
"``**``::"
#: ../../faq/programming.rst:408
msgid "What is the difference between arguments and parameters?"
msgstr "Qual a diferença entre argumentos e parâmetros?"
#: ../../faq/programming.rst:410
msgid ""
":term:`Parameters <parameter>` are defined by the names that appear in a "
"function definition, whereas :term:`arguments <argument>` are the values "
"actually passed to a function when calling it. Parameters define what types "
"of arguments a function can accept. For example, given the function "
"definition::"
msgstr ""
":term:`Parâmetros <parameter>` são definidos pelos nomes que aparecem na "
"definição da função, enquanto :term:`argumentos <argument>` 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 tipos de argumentos que uma "
"função pode receber. Por exemplo, dada a definição da função::"
#: ../../faq/programming.rst:418
msgid ""
"*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling "
"``func``, for example::"
msgstr ""
"*foo*, *bar* e *kwargs* são parâmetros de ``func``. Dessa forma, ao invocar "
"``func``, por exemplo::"
#: ../../faq/programming.rst:423
msgid "the values ``42``, ``314``, and ``somevar`` are arguments."
msgstr "os valores ``42``, ``314``, e ``algumvalor`` são os argumentos."
#: ../../faq/programming.rst:427
msgid "Why did changing list 'y' also change list 'x'?"
msgstr "Por que ao alterar a lista 'y' também altera a lista 'x'?"
#: ../../faq/programming.rst:429
msgid "If you wrote code like::"
msgstr "Se você escreveu um código como::"
#: ../../faq/programming.rst:439
msgid ""
"you might be wondering why appending an element to ``y`` changed ``x`` too."
msgstr ""
"pode estar se perguntando por que acrescentar um elemento a ``y`` também "
"mudou ``x``."
#: ../../faq/programming.rst:441
msgid "There are two factors that produce this result:"
msgstr "Há dois fatores que produzem esse resultado:"
#: ../../faq/programming.rst:443
msgid ""
"Variables are simply names that refer to objects. Doing ``y = x`` doesn't "
"create a copy of the list -- it creates a new variable ``y`` that refers to "
"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. 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:447
msgid ""
"Lists are :term:`mutable`, which means that you can change their content."
msgstr ""
"Listas são objetos :term:`mutáveis <mutável>`, o que significa que você pode "
"alterar o seu conteúdo."
#: ../../faq/programming.rst:449
msgid ""
"After the call to :meth:`~list.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 invocar para :meth:`~list.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:453
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 ""
"we can see that in this case ``x`` and ``y`` are not equal anymore. This is "
"because integers are :term:`immutable`, and when we do ``x = x + 1`` we are "
"not mutating the int ``5`` by incrementing its value; instead, we are "
"creating a new object (the int ``6``) and assigning it to ``x`` (that is, "
"changing which object ``x`` refers to). After this assignment we have two "
"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 ""
"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 <imutável>`, 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:471
msgid ""
"Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the "
"object, whereas superficially similar operations (for example ``y = y + "
"[10]`` and ``sorted(y)``) create a new object. In general in Python (and in "
"all cases in the standard library) a method that mutates an object will "
"return ``None`` to help avoid getting the two types of operations confused. "
"So if you mistakenly write ``y.sort()`` thinking it 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 ``sorted(y)``) cria um novo objeto. Em geral em Python (e em "
"todos os casos na biblioteca padrão) um método que transforma 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:480
msgid ""
"However, there is one class of operations where the same operation sometimes "
"has different behaviors with different types: the augmented assignment "
"operators. For example, ``+=`` mutates lists but not tuples or ints "
"(``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and "
"mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += "
"1`` create new objects)."
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 "
"(``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:487
msgid "In other words:"
msgstr "Em outras palavras:"
#: ../../faq/programming.rst:489
msgid ""
"If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`, "
"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 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:492
msgid ""
"If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`, "
"etc.), all the variables that refer to it will always see the same value, "
"but operations that transform that value into a new value always return a "
"new object."
msgstr ""
"Caso tenhamos um objeto imutável (:class:`str`, :class:`int`, :class:"
"`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:497
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 ""
"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:502
msgid "How do I write a function with output parameters (call by reference)?"
msgstr ""
"Como escrevo uma função com parâmetros de saída (chamada por referência)?"
#: ../../faq/programming.rst:504
msgid ""
"Remember that arguments are passed by assignment in Python. Since "
"assignment just creates references to objects, there's no alias between an "
"argument name in the caller and callee, and so no call-by-reference per se. "
"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 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:509
msgid "By returning a tuple of the results::"
msgstr "Retornando um tupla com os resultados::"
#: ../../faq/programming.rst:520
msgid "This is almost always the clearest solution."
msgstr "Esta é quase sempre a solução mais clara."
#: ../../faq/programming.rst:522
msgid ""
"By using global variables. This isn't thread-safe, and is not recommended."
msgstr ""
"Utilizando variáveis globais. Essa forma não é segura para thread e, "
"portanto, não é recomendada."
#: ../../faq/programming.rst:524
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:535
msgid "By passing in a dictionary that gets mutated::"
msgstr "Pela passagem de um dicionário que sofra mutação::"
#: ../../faq/programming.rst:546
msgid "Or bundle up values in a class instance::"
msgstr "Ou agrupando valores numa instância de classe::"
#: ../../faq/programming.rst:563
msgid "There's almost never a good reason to get this complicated."
msgstr "Quase nunca existe uma boa razão para complicar isso."
#: ../../faq/programming.rst:565
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 "
"resultados."
#: ../../faq/programming.rst:569
msgid "How do you make a higher order function in Python?"
msgstr "Como fazer uma função de ordem superior em Python?"
#: ../../faq/programming.rst:571
msgid ""
"You have two choices: you can use nested scopes or you can use callable "
"objects. For example, suppose you wanted to define ``linear(a,b)`` which "
"returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested "
"scopes::"
msgstr ""
"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:580
msgid "Or using a callable object::"
msgstr "Ou utilizando um objeto chamável::"
#: ../../faq/programming.rst:590
msgid "In both cases, ::"
msgstr "Em ambos os casos::"
#: ../../faq/programming.rst:594
msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``."
msgstr "resulta em um objeto chamável, onde ``taxes(10e6) == 0.3 * 10e6 + 2``."
#: ../../faq/programming.rst:596
msgid ""
"The callable object approach has the disadvantage that it is a bit slower "
"and results in slightly longer code. However, note that a collection of "
"callables can share their signature via inheritance::"
msgstr ""
"A abordagem do objeto chamável tem a desvantagem de que é um pouco mais "
"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:605
msgid "Object can encapsulate state for several methods::"
msgstr "Objetos podem encapsular o estado para vários métodos::"
#: ../../faq/programming.rst:623
msgid ""
"Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the "
"same counting variable."
msgstr ""
"Aqui ``inc()``, ``dec()`` e ``reset()`` funcionam como funções que "