portugython 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- portugython-0.2.0/CHANGELOG.md +70 -0
- {portugython-0.1.0 → portugython-0.2.0}/PKG-INFO +1 -1
- {portugython-0.1.0 → portugython-0.2.0}/portugython/__init__.py +3 -3
- portugython-0.2.0/portugython/abstrato.py +14 -0
- portugython-0.2.0/portugython/argumentos.py +44 -0
- portugython-0.2.0/portugython/assincronico.py +87 -0
- portugython-0.2.0/portugython/bisecao.py +106 -0
- portugython-0.2.0/portugython/calendario.py +70 -0
- portugython-0.2.0/portugython/caminho.py +132 -0
- portugython-0.2.0/portugython/classe_dados.py +40 -0
- portugython-0.2.0/portugython/codificacao.py +95 -0
- portugython-0.2.0/portugython/compressao.py +58 -0
- portugython-0.2.0/portugython/configuracao.py +70 -0
- portugython-0.2.0/portugython/contexto.py +21 -0
- portugython-0.2.0/portugython/copia.py +28 -0
- portugython-0.2.0/portugython/csv_pt.py +46 -0
- portugython-0.2.0/portugython/depuracao.py +122 -0
- portugython-0.2.0/portugython/enumeracao.py +17 -0
- portugython-0.2.0/portugython/estatistica.py +81 -0
- portugython-0.2.0/portugython/estrutura.py +73 -0
- portugython-0.2.0/portugython/formatacao.py +118 -0
- portugython-0.2.0/portugython/hash_pt.py +96 -0
- portugython-0.2.0/portugython/identificador.py +45 -0
- portugython-0.2.0/portugython/json.py +71 -0
- portugython-0.2.0/portugython/rede.py +129 -0
- portugython-0.2.0/portugython/registro.py +64 -0
- portugython-0.2.0/portugython/serializacao.py +55 -0
- portugython-0.2.0/portugython/soquete.py +75 -0
- portugython-0.2.0/portugython/subprocesso.py +91 -0
- portugython-0.2.0/portugython/threads.py +110 -0
- portugython-0.2.0/portugython/tipagem.py +83 -0
- {portugython-0.1.0 → portugython-0.2.0}/pyproject.toml +1 -1
- {portugython-0.1.0 → portugython-0.2.0}/tests/test_portugython.py +1 -1
- portugython-0.2.0/tests/test_submodulos.py +433 -0
- portugython-0.1.0/CHANGELOG.md +0 -31
- portugython-0.1.0/tests/test_submodulos.py +0 -217
- {portugython-0.1.0 → portugython-0.2.0}/.gitignore +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/LICENSE +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/README.md +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/aleatorio.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/colecoes.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/expressao.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/funcional.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/iteradores.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/matematica.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/py.typed +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/sistema.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/portugython/tempo.py +0 -0
- {portugython-0.1.0 → portugython-0.2.0}/tests/__init__.py +0 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0 (2026-06-26)
|
|
4
|
+
|
|
5
|
+
Full stdlib coverage. 36 submodules total, all importable via `from portugython import <modulo>`:
|
|
6
|
+
|
|
7
|
+
**New in 0.2.0:**
|
|
8
|
+
- `caminho` (pathlib): Caminho com existe, eh_arquivo, listar, ler_texto, escrever_texto, etc.
|
|
9
|
+
- `json`: serializar, deserializar, serializar_arquivo, deserializar_arquivo
|
|
10
|
+
- `estatistica` (statistics): media, mediana, moda, desvio_padrao, covariancia, correlacao, quantis
|
|
11
|
+
- `enumeracao` (enum): Enumeracao, EnumeracaoInteira, EnumeracaoBandeira, automatico, unico
|
|
12
|
+
- `classe_dados` (dataclasses): classe_dados, campo, para_dicionario, para_tupla, substituir
|
|
13
|
+
- `contexto` (contextlib): gerenciador, suprimir, fechar_ao_sair, pilha_saida
|
|
14
|
+
- `tipagem` (typing): re-exporta todos os tipos com nomes em Portugues
|
|
15
|
+
- `csv_pt` (csv): ler_csv, escrever_csv, LeitorCSV, EscritorCSV, LeitorDicionario
|
|
16
|
+
- `registro` (logging): obter_registrador, configurar_registro, depurar, informar, avisar, erro
|
|
17
|
+
- `argumentos` (argparse): AnalisadorArgumentos com adicionar_argumento, analisar
|
|
18
|
+
- `subprocesso` (subprocess): executar, executar_shell, saida, chamar
|
|
19
|
+
- `copia` (copy): copiar, copiar_profundo
|
|
20
|
+
- `hash_pt` (hashlib + hmac): md5, sha256, sha512, blake2b, codigo_autenticacao, comparar_seguro
|
|
21
|
+
- `threads` (threading): Thread, Semaforo, Evento, Trava, contagem_threads, thread_atual
|
|
22
|
+
- `abstrato` (abc): ClasseAbstrata, metodo_abstrato, propriedade_abstrata
|
|
23
|
+
- `bisecao` (bisect + heapq): inserir_ordenado, buscar_ordenado, heapificar, empurrar, n_maiores
|
|
24
|
+
- `identificador` (uuid): uuid1, uuid3, uuid4, uuid5
|
|
25
|
+
- `calendario` (calendar): dias_no_mes, eh_ano_bissexto, dia_semana, calendario_mes
|
|
26
|
+
- `configuracao` (configparser): AnalisadorConfig com ler_arquivo, obter, definir, escrever_arquivo
|
|
27
|
+
- `serializacao` (pickle): serializar, deserializar, serializar_arquivo, deserializar_arquivo
|
|
28
|
+
- `codificacao` (base64 + codecs): para_base64, de_base64, para_base32, para_base16
|
|
29
|
+
- `compressao` (gzip + zlib): comprimir_gzip, descomprimir_gzip, comprimir_zlib
|
|
30
|
+
- `formatacao` (textwrap + pprint + string): quebrar, preencher, dedenter, recuar, imprimir_bonito
|
|
31
|
+
- `depuracao` (traceback + warnings + gc): imprimir_excecao, formatar_excecao, coletar_lixo
|
|
32
|
+
- `soquete` (socket): Soquete, criar_conexao, criar_servidor, nome_host, endereco_ip
|
|
33
|
+
- `assincronico` (asyncio): executar, criar_tarefa, dormir, reunir, Evento, Fila
|
|
34
|
+
- `estrutura` (struct): empacotar, desempacotar, calcular_tamanho
|
|
35
|
+
- `rede` (urllib + http): baixar_url, abrir_url, analisar_url, codificar_url, codificar_parametros
|
|
36
|
+
|
|
37
|
+
Also in 0.2.0:
|
|
38
|
+
- Fix: renamed builtin `identificador` alias to `obter_id` to avoid shadowing the uuid submodule
|
|
39
|
+
- 49 tests covering all modules
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
## 0.1.0 (2026-06-26)
|
|
43
|
+
|
|
44
|
+
- Add full stdlib submodule set with Portuguese translations:
|
|
45
|
+
- `aleatorio` (random): escolha, embaralhe, amostra, gauss, normal, etc.
|
|
46
|
+
- `matematica` (math): raiz_quadrada, seno, cosseno, fatorial, mdc, mmc, etc.
|
|
47
|
+
- `sistema` (os + sys): diretorio_atual, listar_diretorio, existe, sair, etc.
|
|
48
|
+
- `tempo` (time + datetime): Data, Hora, DataHora, Duracao, agora, hoje, dormir, etc.
|
|
49
|
+
- `colecoes` (collections): Contador, Deque, DicionarioOrdenado, Pilha, Fila, etc.
|
|
50
|
+
- `iteradores` (itertools): encadeie, combine, permute, acumule, agrupe, etc.
|
|
51
|
+
- `funcional` (functools): reduzido, parcial, cache, compor, negado, etc.
|
|
52
|
+
- `expressao` (re): compilar, buscar, substituir, encontrar_todos, Padrao, etc.
|
|
53
|
+
- Rewrite `__init__.py` with clean Portuguese names (remove `_pt` suffixes)
|
|
54
|
+
- Add `Conjunto` class with Portuguese methods
|
|
55
|
+
- Expand `Texto`, `Lista`, `Dicionario` with more methods
|
|
56
|
+
- Add more exception types: ErroArquivo, ErroPermissao, ErroRecursao, ErroPausa
|
|
57
|
+
- Bump minimum Python to >=3.10
|
|
58
|
+
- 30 tests across all modules
|
|
59
|
+
|
|
60
|
+
## 0.0.15 (2026-06-26)
|
|
61
|
+
|
|
62
|
+
- Add Portuguese translations of Python builtins and core functions
|
|
63
|
+
- Introduce Lista, Dicionario, Texto classes with Portuguese methods
|
|
64
|
+
- Add helper functions: se(), para_cada(), filtro()
|
|
65
|
+
- Add Portuguese exception classes
|
|
66
|
+
- Expand test suite
|
|
67
|
+
|
|
68
|
+
## 0.0.14 (2022-11-28)
|
|
69
|
+
|
|
70
|
+
- Latest release on PyPI.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: portugython
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A Portuguese translation of the Python functions/modules/packages
|
|
5
5
|
Project-URL: Homepage, https://github.com/spacemany2k38/portugython
|
|
6
6
|
Project-URL: Bug Tracker, https://github.com/spacemany2k38/portugython/issues
|
|
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from functools import reduce as _reduce
|
|
6
6
|
|
|
7
|
-
__version__ = "0.
|
|
7
|
+
__version__ = "0.2.0"
|
|
8
8
|
|
|
9
9
|
# ---------------------------------------------------------------------------
|
|
10
10
|
# IO
|
|
@@ -48,7 +48,7 @@ tipo = type
|
|
|
48
48
|
chamavel = callable
|
|
49
49
|
e_instancia = isinstance
|
|
50
50
|
e_subclasse = issubclass
|
|
51
|
-
|
|
51
|
+
obter_id = id
|
|
52
52
|
atributos = dir
|
|
53
53
|
obter_atributo = getattr
|
|
54
54
|
definir_atributo = setattr
|
|
@@ -522,7 +522,7 @@ __all__ = [
|
|
|
522
522
|
"chamavel",
|
|
523
523
|
"e_instancia",
|
|
524
524
|
"e_subclasse",
|
|
525
|
-
"
|
|
525
|
+
"obter_id",
|
|
526
526
|
"atributos",
|
|
527
527
|
"obter_atributo",
|
|
528
528
|
"definir_atributo",
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""abstrato - traducao em Portugues do modulo abc."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import abc as _abc
|
|
5
|
+
|
|
6
|
+
__all__ = ["ClasseAbstrata", "metodo_abstrato", "propriedade_abstrata", "ABCMeta"]
|
|
7
|
+
|
|
8
|
+
ClasseAbstrata = _abc.ABC
|
|
9
|
+
metodo_abstrato = _abc.abstractmethod
|
|
10
|
+
ABCMeta = _abc.ABCMeta
|
|
11
|
+
|
|
12
|
+
def propriedade_abstrata(func):
|
|
13
|
+
"""Decorator para propriedades abstratas."""
|
|
14
|
+
return property(_abc.abstractmethod(func))
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""argumentos - traducao em Portugues do modulo argparse."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse as _ap
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AnalisadorArgumentos", "EspacoNomes", "AcaoAdicionar",
|
|
8
|
+
"AcaoVerdadeiro", "AcaoFalso", "AcaoContar",
|
|
9
|
+
"ErroArgumento",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
ErroArgumento = _ap.ArgumentError
|
|
13
|
+
EspacoNomes = _ap.Namespace
|
|
14
|
+
AcaoAdicionar = "append"
|
|
15
|
+
AcaoVerdadeiro = "store_true"
|
|
16
|
+
AcaoFalso = "store_false"
|
|
17
|
+
AcaoContar = "count"
|
|
18
|
+
|
|
19
|
+
class AnalisadorArgumentos(_ap.ArgumentParser):
|
|
20
|
+
"""ArgumentParser com metodos em Portugues."""
|
|
21
|
+
|
|
22
|
+
def adicionar_argumento(self, *nomes, **kwargs) -> None:
|
|
23
|
+
"""Adiciona um argumento ao analisador."""
|
|
24
|
+
self.add_argument(*nomes, **kwargs)
|
|
25
|
+
|
|
26
|
+
def analisar(self, args=None) -> _ap.Namespace:
|
|
27
|
+
"""Analisa os argumentos da linha de comando."""
|
|
28
|
+
return self.parse_args(args)
|
|
29
|
+
|
|
30
|
+
def analisar_parcial(self, args=None) -> tuple:
|
|
31
|
+
"""Analisa os argumentos conhecidos, ignorando os desconhecidos."""
|
|
32
|
+
return self.parse_known_args(args)
|
|
33
|
+
|
|
34
|
+
def adicionar_subcomandos(self, **kwargs) -> _ap.Action:
|
|
35
|
+
"""Adiciona suporte a subcomandos."""
|
|
36
|
+
return self.add_subparsers(**kwargs)
|
|
37
|
+
|
|
38
|
+
def adicionar_grupo(self, titulo: str = "", descricao: str = ""):
|
|
39
|
+
"""Adiciona um grupo de argumentos."""
|
|
40
|
+
return self.add_argument_group(titulo, descricao)
|
|
41
|
+
|
|
42
|
+
def adicionar_grupo_exclusivo(self, obrigatorio: bool = False):
|
|
43
|
+
"""Adiciona um grupo mutualmente exclusivo."""
|
|
44
|
+
return self.add_mutually_exclusive_group(required=obrigatorio)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""assincronico - traducao em Portugues do modulo asyncio."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio as _aio
|
|
5
|
+
from typing import Any, Coroutine
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"executar", "esperar", "criar_tarefa", "dormir",
|
|
9
|
+
"reunir", "timeout", "cancelar_ao_timeout",
|
|
10
|
+
"Evento", "Fila", "Semaforo", "Trava",
|
|
11
|
+
"obter_laco", "novo_laco", "LacoEventos",
|
|
12
|
+
"corrotina", "eh_corrotina", "eh_aguardavel",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
LacoEventos = _aio.AbstractEventLoop
|
|
16
|
+
Evento = _aio.Event
|
|
17
|
+
Fila = _aio.Queue
|
|
18
|
+
Semaforo = _aio.Semaphore
|
|
19
|
+
Trava = _aio.Lock
|
|
20
|
+
corrotina = _aio.coroutine if hasattr(_aio, "coroutine") else None
|
|
21
|
+
|
|
22
|
+
def executar(corrotina_principal: Coroutine, *, depurar: bool = False) -> Any:
|
|
23
|
+
"""Executa uma corrotina como programa principal.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
corrotina_principal: Corrotina a executar.
|
|
27
|
+
depurar: Habilita modo de depuracao.
|
|
28
|
+
"""
|
|
29
|
+
return _aio.run(corrotina_principal, debug=depurar)
|
|
30
|
+
|
|
31
|
+
async def esperar(aguardavel: Any) -> Any:
|
|
32
|
+
"""Aguarda um aguardavel e retorna o resultado.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
aguardavel: Corrotina, Task ou Future a aguardar.
|
|
36
|
+
"""
|
|
37
|
+
return await _aio.ensure_future(aguardavel)
|
|
38
|
+
|
|
39
|
+
def criar_tarefa(corrotina: Coroutine, *, nome: str | None = None) -> _aio.Task:
|
|
40
|
+
"""Cria uma Task a partir de uma corrotina.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
corrotina: Corrotina a executar como tarefa.
|
|
44
|
+
nome: Nome opcional da tarefa.
|
|
45
|
+
"""
|
|
46
|
+
return _aio.create_task(corrotina, name=nome)
|
|
47
|
+
|
|
48
|
+
async def dormir(segundos: float) -> None:
|
|
49
|
+
"""Suspende a corrotina pelo tempo especificado.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
segundos: Tempo de espera em segundos.
|
|
53
|
+
"""
|
|
54
|
+
await _aio.sleep(segundos)
|
|
55
|
+
|
|
56
|
+
async def reunir(*aguardaveis: Any, retornar_excecoes: bool = False) -> list:
|
|
57
|
+
"""Executa multiplos aguardaveis concorrentemente.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
*aguardaveis: Corrotinas ou Tasks a executar.
|
|
61
|
+
retornar_excecoes: Se True, excecoes sao retornadas em vez de propagadas.
|
|
62
|
+
"""
|
|
63
|
+
return await _aio.gather(*aguardaveis, return_exceptions=retornar_excecoes)
|
|
64
|
+
|
|
65
|
+
def timeout(delay: float):
|
|
66
|
+
"""Context manager que cancela a operacao apos delay segundos."""
|
|
67
|
+
return _aio.timeout(delay)
|
|
68
|
+
|
|
69
|
+
def cancelar_ao_timeout(delay: float):
|
|
70
|
+
"""Context manager que cancela apos delay (compat anterior)."""
|
|
71
|
+
return _aio.timeout(delay)
|
|
72
|
+
|
|
73
|
+
def obter_laco() -> _aio.AbstractEventLoop:
|
|
74
|
+
"""Retorna o laco de eventos em execucao."""
|
|
75
|
+
return _aio.get_event_loop()
|
|
76
|
+
|
|
77
|
+
def novo_laco() -> _aio.AbstractEventLoop:
|
|
78
|
+
"""Cria e retorna um novo laco de eventos."""
|
|
79
|
+
return _aio.new_event_loop()
|
|
80
|
+
|
|
81
|
+
def eh_corrotina(obj: Any) -> bool:
|
|
82
|
+
"""Retorna True se obj for uma corrotina."""
|
|
83
|
+
return _aio.iscoroutine(obj)
|
|
84
|
+
|
|
85
|
+
def eh_aguardavel(obj: Any) -> bool:
|
|
86
|
+
"""Retorna True se obj for aguardavel."""
|
|
87
|
+
return _aio.isfuture(obj) or _aio.iscoroutine(obj) or _aio.iscoroutinefunction(obj)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""bisecao - traducao em Portugues dos modulos bisect e heapq."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import bisect as _bis
|
|
5
|
+
import heapq as _hq
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
# bisect
|
|
10
|
+
"inserir_esquerda", "inserir_direita", "buscar_esquerda", "buscar_direita",
|
|
11
|
+
# heapq
|
|
12
|
+
"heapificar", "empurrar", "retirar", "empurrar_retirar", "retirar_empurrar",
|
|
13
|
+
"n_maiores", "n_menores", "fundir",
|
|
14
|
+
# alias
|
|
15
|
+
"inserir_ordenado", "buscar_ordenado",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
def inserir_esquerda(
|
|
19
|
+
lista: list, item: Any, inicio: int = 0, fim: int | None = None
|
|
20
|
+
) -> None:
|
|
21
|
+
"""Insere item na lista ordenada, a esquerda de iguais.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
lista: Lista ordenada.
|
|
25
|
+
item: Item a inserir.
|
|
26
|
+
inicio: Indice de inicio da busca.
|
|
27
|
+
fim: Indice de fim da busca.
|
|
28
|
+
"""
|
|
29
|
+
if fim is None:
|
|
30
|
+
_bis.insort_left(lista, item, inicio)
|
|
31
|
+
else:
|
|
32
|
+
_bis.insort_left(lista, item, inicio, fim)
|
|
33
|
+
|
|
34
|
+
def inserir_direita(
|
|
35
|
+
lista: list, item: Any, inicio: int = 0, fim: int | None = None
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Insere item na lista ordenada, a direita de iguais."""
|
|
38
|
+
if fim is None:
|
|
39
|
+
_bis.insort_right(lista, item, inicio)
|
|
40
|
+
else:
|
|
41
|
+
_bis.insort_right(lista, item, inicio, fim)
|
|
42
|
+
|
|
43
|
+
inserir_ordenado = inserir_direita
|
|
44
|
+
|
|
45
|
+
def buscar_esquerda(
|
|
46
|
+
lista: list, item: Any, inicio: int = 0, fim: int | None = None
|
|
47
|
+
) -> int:
|
|
48
|
+
"""Retorna o indice de insercao a esquerda de iguais."""
|
|
49
|
+
if fim is None:
|
|
50
|
+
return _bis.bisect_left(lista, item, inicio)
|
|
51
|
+
return _bis.bisect_left(lista, item, inicio, fim)
|
|
52
|
+
|
|
53
|
+
def buscar_direita(
|
|
54
|
+
lista: list, item: Any, inicio: int = 0, fim: int | None = None
|
|
55
|
+
) -> int:
|
|
56
|
+
"""Retorna o indice de insercao a direita de iguais."""
|
|
57
|
+
if fim is None:
|
|
58
|
+
return _bis.bisect_right(lista, item, inicio)
|
|
59
|
+
return _bis.bisect_right(lista, item, inicio, fim)
|
|
60
|
+
|
|
61
|
+
buscar_ordenado = buscar_direita
|
|
62
|
+
|
|
63
|
+
def heapificar(lista: list) -> None:
|
|
64
|
+
"""Converte uma lista em heap no lugar (min-heap).
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
lista: Lista a converter.
|
|
68
|
+
"""
|
|
69
|
+
_hq.heapify(lista)
|
|
70
|
+
|
|
71
|
+
def empurrar(heap: list, item: Any) -> None:
|
|
72
|
+
"""Adiciona item ao heap mantendo a propriedade de heap.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
heap: Heap existente.
|
|
76
|
+
item: Item a adicionar.
|
|
77
|
+
"""
|
|
78
|
+
_hq.heappush(heap, item)
|
|
79
|
+
|
|
80
|
+
def retirar(heap: list) -> Any:
|
|
81
|
+
"""Remove e retorna o menor item do heap.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
heap: Heap existente.
|
|
85
|
+
"""
|
|
86
|
+
return _hq.heappop(heap)
|
|
87
|
+
|
|
88
|
+
def empurrar_retirar(heap: list, item: Any) -> Any:
|
|
89
|
+
"""Empurra item e retira o menor de forma eficiente."""
|
|
90
|
+
return _hq.heappushpop(heap, item)
|
|
91
|
+
|
|
92
|
+
def retirar_empurrar(heap: list, item: Any) -> Any:
|
|
93
|
+
"""Retira o menor e empurra item de forma eficiente."""
|
|
94
|
+
return _hq.heapreplace(heap, item)
|
|
95
|
+
|
|
96
|
+
def n_maiores(n: int, iteravel: Any, chave=None) -> list:
|
|
97
|
+
"""Retorna os n maiores elementos do iteravel."""
|
|
98
|
+
return _hq.nlargest(n, iteravel, key=chave)
|
|
99
|
+
|
|
100
|
+
def n_menores(n: int, iteravel: Any, chave=None) -> list:
|
|
101
|
+
"""Retorna os n menores elementos do iteravel."""
|
|
102
|
+
return _hq.nsmallest(n, iteravel, key=chave)
|
|
103
|
+
|
|
104
|
+
def fundir(*iteraveis: Any, chave=None) -> Any:
|
|
105
|
+
"""Funde iteraveis ordenados em um unico iteravel ordenado."""
|
|
106
|
+
return _hq.merge(*iteraveis, key=chave)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""calendario - traducao em Portugues do modulo calendar."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import calendar as _cal
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"calendario_mes", "calendario_ano", "dias_no_mes", "eh_ano_bissexto",
|
|
8
|
+
"dia_semana", "dias_semana", "meses",
|
|
9
|
+
"SEGUNDA", "TERCA", "QUARTA", "QUINTA", "SEXTA", "SABADO", "DOMINGO",
|
|
10
|
+
"Calendario", "CalendarioTexto",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
SEGUNDA = _cal.MONDAY
|
|
14
|
+
TERCA = _cal.TUESDAY
|
|
15
|
+
QUARTA = _cal.WEDNESDAY
|
|
16
|
+
QUINTA = _cal.THURSDAY
|
|
17
|
+
SEXTA = _cal.FRIDAY
|
|
18
|
+
SABADO = _cal.SATURDAY
|
|
19
|
+
DOMINGO = _cal.SUNDAY
|
|
20
|
+
|
|
21
|
+
dias_semana = list(_cal.day_name)
|
|
22
|
+
meses = list(_cal.month_name)[1:]
|
|
23
|
+
|
|
24
|
+
Calendario = _cal.Calendar
|
|
25
|
+
CalendarioTexto = _cal.TextCalendar
|
|
26
|
+
|
|
27
|
+
def calendario_mes(ano: int, mes: int, largura: int = 0) -> str:
|
|
28
|
+
"""Retorna o calendario de um mes como texto.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
ano: Ano.
|
|
32
|
+
mes: Mes (1-12).
|
|
33
|
+
largura: Largura da coluna de dia.
|
|
34
|
+
"""
|
|
35
|
+
return _cal.month(ano, mes, largura)
|
|
36
|
+
|
|
37
|
+
def calendario_ano(ano: int) -> str:
|
|
38
|
+
"""Retorna o calendario do ano inteiro como texto.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
ano: Ano.
|
|
42
|
+
"""
|
|
43
|
+
return _cal.calendar(ano)
|
|
44
|
+
|
|
45
|
+
def dias_no_mes(ano: int, mes: int) -> int:
|
|
46
|
+
"""Retorna o numero de dias no mes.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
ano: Ano.
|
|
50
|
+
mes: Mes (1-12).
|
|
51
|
+
"""
|
|
52
|
+
return _cal.monthrange(ano, mes)[1]
|
|
53
|
+
|
|
54
|
+
def eh_ano_bissexto(ano: int) -> bool:
|
|
55
|
+
"""Retorna True se o ano for bissexto.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
ano: Ano.
|
|
59
|
+
"""
|
|
60
|
+
return _cal.isleap(ano)
|
|
61
|
+
|
|
62
|
+
def dia_semana(ano: int, mes: int, dia: int) -> int:
|
|
63
|
+
"""Retorna o dia da semana (0=segunda, 6=domingo).
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
ano: Ano.
|
|
67
|
+
mes: Mes (1-12).
|
|
68
|
+
dia: Dia (1-31).
|
|
69
|
+
"""
|
|
70
|
+
return _cal.weekday(ano, mes, dia)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""caminho - traducao em Portugues do modulo pathlib."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import pathlib as _pathlib
|
|
5
|
+
from typing import Iterator
|
|
6
|
+
|
|
7
|
+
__all__ = ["Caminho", "CaminhoPuro", "caminho_atual"]
|
|
8
|
+
|
|
9
|
+
class Caminho(_pathlib.Path):
|
|
10
|
+
"""Path com metodos em Portugues."""
|
|
11
|
+
_flavour = (
|
|
12
|
+
_pathlib.Path('.')._flavour
|
|
13
|
+
if hasattr(_pathlib.Path('.'), '_flavour')
|
|
14
|
+
else None
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
def __new__(cls, *args, **kwargs):
|
|
18
|
+
return super().__new__(cls, *args, **kwargs)
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def atual(cls) -> "Caminho":
|
|
22
|
+
"""Retorna o diretorio de trabalho atual."""
|
|
23
|
+
return cls(_pathlib.Path.cwd())
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def usuario(cls) -> "Caminho":
|
|
27
|
+
"""Retorna o diretorio home do usuario."""
|
|
28
|
+
return cls(_pathlib.Path.home())
|
|
29
|
+
|
|
30
|
+
def existe(self) -> bool:
|
|
31
|
+
"""Retorna True se o caminho existe."""
|
|
32
|
+
return self.exists()
|
|
33
|
+
|
|
34
|
+
def eh_arquivo(self) -> bool:
|
|
35
|
+
"""Retorna True se for um arquivo regular."""
|
|
36
|
+
return self.is_file()
|
|
37
|
+
|
|
38
|
+
def eh_diretorio(self) -> bool:
|
|
39
|
+
"""Retorna True se for um diretorio."""
|
|
40
|
+
return self.is_dir()
|
|
41
|
+
|
|
42
|
+
def eh_link(self) -> bool:
|
|
43
|
+
"""Retorna True se for um link simbolico."""
|
|
44
|
+
return self.is_symlink()
|
|
45
|
+
|
|
46
|
+
def criar(self, existe_ok: bool = False) -> None:
|
|
47
|
+
"""Cria o arquivo (touch)."""
|
|
48
|
+
self.touch(exist_ok=existe_ok)
|
|
49
|
+
|
|
50
|
+
def criar_dir(self, pais: bool = False, existe_ok: bool = False) -> None:
|
|
51
|
+
"""Cria o diretorio."""
|
|
52
|
+
self.mkdir(parents=pais, exist_ok=existe_ok)
|
|
53
|
+
|
|
54
|
+
def remover(self) -> None:
|
|
55
|
+
"""Remove o arquivo."""
|
|
56
|
+
self.unlink()
|
|
57
|
+
|
|
58
|
+
def remover_dir(self) -> None:
|
|
59
|
+
"""Remove o diretorio vazio."""
|
|
60
|
+
self.rmdir()
|
|
61
|
+
|
|
62
|
+
def renomear(self, destino: str | "Caminho") -> "Caminho":
|
|
63
|
+
"""Renomeia e retorna o novo caminho."""
|
|
64
|
+
return Caminho(self.rename(destino))
|
|
65
|
+
|
|
66
|
+
def listar(self) -> Iterator["Caminho"]:
|
|
67
|
+
"""Itera sobre o conteudo do diretorio."""
|
|
68
|
+
return (Caminho(p) for p in self.iterdir())
|
|
69
|
+
|
|
70
|
+
def buscar(self, padrao: str) -> Iterator["Caminho"]:
|
|
71
|
+
"""Busca arquivos que correspondem ao padrao."""
|
|
72
|
+
return (Caminho(p) for p in self.glob(padrao))
|
|
73
|
+
|
|
74
|
+
def buscar_recursivo(self, padrao: str) -> Iterator["Caminho"]:
|
|
75
|
+
"""Busca recursivamente arquivos que correspondem ao padrao."""
|
|
76
|
+
return (Caminho(p) for p in self.rglob(padrao))
|
|
77
|
+
|
|
78
|
+
def ler_texto(self, codificacao: str = "utf-8") -> str:
|
|
79
|
+
"""Le o conteudo como texto."""
|
|
80
|
+
return self.read_text(encoding=codificacao)
|
|
81
|
+
|
|
82
|
+
def escrever_texto(self, conteudo: str, codificacao: str = "utf-8") -> int:
|
|
83
|
+
"""Escreve texto no arquivo."""
|
|
84
|
+
return self.write_text(conteudo, encoding=codificacao)
|
|
85
|
+
|
|
86
|
+
def ler_bytes(self) -> bytes:
|
|
87
|
+
"""Le o conteudo como bytes."""
|
|
88
|
+
return self.read_bytes()
|
|
89
|
+
|
|
90
|
+
def escrever_bytes(self, dados: bytes) -> int:
|
|
91
|
+
"""Escreve bytes no arquivo."""
|
|
92
|
+
return self.write_bytes(dados)
|
|
93
|
+
|
|
94
|
+
def absoluto(self) -> "Caminho":
|
|
95
|
+
"""Retorna o caminho absoluto."""
|
|
96
|
+
return Caminho(self.resolve())
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def nome(self) -> str:
|
|
100
|
+
"""Nome do arquivo com extensao."""
|
|
101
|
+
return self.name
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def sufixo(self) -> str:
|
|
105
|
+
"""Extensao do arquivo."""
|
|
106
|
+
return self.suffix
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def sufixos(self) -> list[str]:
|
|
110
|
+
"""Todas as extensoes."""
|
|
111
|
+
return self.suffixes
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def raiz_nome(self) -> str:
|
|
115
|
+
"""Nome sem extensao."""
|
|
116
|
+
return self.stem
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def pai(self) -> "Caminho":
|
|
120
|
+
"""Diretorio pai."""
|
|
121
|
+
return Caminho(self.parent)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def partes(self) -> tuple[str, ...]:
|
|
125
|
+
"""Componentes do caminho."""
|
|
126
|
+
return self.parts
|
|
127
|
+
|
|
128
|
+
CaminhoPuro = _pathlib.PurePath
|
|
129
|
+
|
|
130
|
+
def caminho_atual() -> Caminho:
|
|
131
|
+
"""Retorna o diretorio de trabalho atual."""
|
|
132
|
+
return Caminho.atual()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""classe_dados - traducao em Portugues do modulo dataclasses."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import dataclasses as _dc
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"classe_dados", "campo", "Campo", "fabrica_campo",
|
|
9
|
+
"para_dicionario", "para_tupla", "eh_classe_dados",
|
|
10
|
+
"eh_instancia_classe_dados", "campos", "substituir",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
classe_dados = _dc.dataclass
|
|
14
|
+
campo = _dc.field
|
|
15
|
+
Campo = _dc.Field
|
|
16
|
+
fabrica_campo = _dc.fields
|
|
17
|
+
|
|
18
|
+
def para_dicionario(instancia: Any) -> dict:
|
|
19
|
+
"""Converte uma instancia de classe_dados em dicionario."""
|
|
20
|
+
return _dc.asdict(instancia)
|
|
21
|
+
|
|
22
|
+
def para_tupla(instancia: Any) -> tuple:
|
|
23
|
+
"""Converte uma instancia de classe_dados em tupla."""
|
|
24
|
+
return _dc.astuple(instancia)
|
|
25
|
+
|
|
26
|
+
def eh_classe_dados(cls: Any) -> bool:
|
|
27
|
+
"""Retorna True se cls e uma classe decorada com @classe_dados."""
|
|
28
|
+
return _dc.is_dataclass(cls) and isinstance(cls, type)
|
|
29
|
+
|
|
30
|
+
def eh_instancia_classe_dados(obj: Any) -> bool:
|
|
31
|
+
"""Retorna True se obj e uma instancia de classe_dados."""
|
|
32
|
+
return _dc.is_dataclass(obj) and not isinstance(obj, type)
|
|
33
|
+
|
|
34
|
+
def campos(cls: Any) -> tuple:
|
|
35
|
+
"""Retorna os campos de uma classe_dados."""
|
|
36
|
+
return _dc.fields(cls)
|
|
37
|
+
|
|
38
|
+
def substituir(instancia: Any, **alteracoes: Any) -> Any:
|
|
39
|
+
"""Cria uma nova instancia substituindo campos especificados."""
|
|
40
|
+
return _dc.replace(instancia, **alteracoes)
|