pyinterfaces 0.0.1__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.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyinterfaces
3
+ Version: 0.2.0
4
+ Summary: Interface in POO with Python
5
+ License-Expression: MIT
6
+ License-File: license.txt
7
+ Keywords: interface,java,syntax,brunozolotareff,pyinterfaces
8
+ Author: Bruno Zolotareff
9
+ Author-email: brunozolotareff@gmail.com
10
+ Requires-Python: >=3.10
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Description-Content-Type: text/markdown
18
+
19
+ # pyinterfaces
20
+
21
+ A lightweight Python compiler extension that brings clean, Java-style interface syntax to Python using native braces `{}`.
22
+
23
+ [![PyPI version](https://shields.io)](https://pypi.org)
24
+ [![Python Versions](https://shields.io)](https://pypi.org)
25
+
26
+ ---
27
+
28
+ ## 📐 Why pyinterfaces? (Software Engineering Perspective)
29
+
30
+ In modern **Software Engineering**, separating *definition* from *implementation* is a core architectural principle.
31
+ Following SOLID principles—specifically the **Interface Segregation Principle (ISP)** and the **Dependency Inversion Principle (DIP)**—software components should depend on abstractions (interfaces), not on concrete logic.
32
+
33
+ While standard Python uses `abc.ABC` and `@abstractmethod` to enforce contracts, the syntax can often look cluttered, repetitive, and conceptually muddy (as Python abstract classes can accidentally mix actual logic with abstract models).
34
+
35
+ **`pyinterfaces`** bridges this gap by enforcing **Pure Interfaces**. It allows software engineers to declare strict structural contracts using the familiar, elegant, and universally understood Java/C# layout, keeping your architecture clean and highly readable.
36
+
37
+ ---
38
+
39
+ ## ✨ Features
40
+
41
+ - **Java-Style Syntax**: Declare structures using `Interface Name { ... }`.
42
+ - **Pure Abstraction**: No mixed implementation code allowed inside the contract block.
43
+ - **Runtime Enforcement**: Automatically triggers native Python `abc` validations under the hood.
44
+ - **Zero Overhead**: Translated seamlessly during file tokenization using custom stream decoding.
45
+
46
+ ---
47
+
48
+ ## 🚀 Installation
49
+
50
+ You can install `pyinterfaces` via `pip` or add it to your project using `poetry`:
51
+
52
+ ```bash
53
+ pip install pyinterfaces
54
+ ```
55
+
56
+ Or with Poetry:
57
+ ```bash
58
+ poetry add pyinterfaces
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 💻 Usage
64
+
65
+ To enable the custom Java-like syntax parsing, you **must** include the magic encoding comment `# -*- coding: java_interface -*-` at the very first line of your Python script.
66
+
67
+ Here is a standard example of designing a decoupled Payment System:
68
+
69
+ ```python
70
+ # -*- coding: java_interface -*-
71
+ import pyinterfaces
72
+
73
+ # 1. Define the pure architectural contract
74
+ Interface PaymentProcessor {
75
+ process_payment(self, amount: float) -> bool
76
+ refund_payment(self, transaction_id: str) -> None
77
+ }
78
+
79
+ # 2. Implement the contract in standard Python classes
80
+ class PixProcessor(PaymentProcessor):
81
+ def process_payment(self, amount: float) -> bool:
82
+ print(f"Processing R\${amount} instantly via Pix.")
83
+ return True
84
+
85
+ def refund_payment(self, transaction_id: str) -> None:
86
+ print(f"Refunding transaction {transaction_id}.")
87
+
88
+ # 3. Compile-time / Runtime validation
89
+ class BrokenProcessor(PaymentProcessor):
90
+ def process_payment(self, amount: float) -> bool:
91
+ return True
92
+ # ERROR! Missing 'refund_payment' method implementation.
93
+ ```
94
+
95
+ If a developer attempts to instantiate `BrokenProcessor`, Python will instantly raise a `TypeError`, stating that the class failed to implement the strict contract requirements defined by your interface.
96
+
97
+ ---
98
+
99
+ ## 🛠️ How it works under the hood
100
+
101
+ `pyinterfaces` hooks directly into Python's native `codecs` registry. When the interpretator reads the `# -*- coding: java_interface -*-` header, it streams your file through our custom pre-processor, safely transforming the custom block syntax into fully valid standard Python `abc.ABC` structures before the code even executes.
102
+
103
+ ---
104
+
105
+ ## 👤 Author
106
+
107
+ - Created and maintained by **Bruno Zolotareff**
108
+ - PyPI Repository: [https://pypi.org](https://pypi.org)
109
+
110
+ ## 🤝 Acknowledgments
111
+
112
+ Special thanks to my friend **Leandro Reginaldo** for collaborating on the original concept, brainstorming the architectural ideas, and helping to shape the vision of `pyinterfaces`. This project wouldn't be the same without your insights!
113
+
114
+
115
+ ## 📄 License
116
+
117
+ This project is licensed under the MIT License.
@@ -0,0 +1,99 @@
1
+ # pyinterfaces
2
+
3
+ A lightweight Python compiler extension that brings clean, Java-style interface syntax to Python using native braces `{}`.
4
+
5
+ [![PyPI version](https://shields.io)](https://pypi.org)
6
+ [![Python Versions](https://shields.io)](https://pypi.org)
7
+
8
+ ---
9
+
10
+ ## 📐 Why pyinterfaces? (Software Engineering Perspective)
11
+
12
+ In modern **Software Engineering**, separating *definition* from *implementation* is a core architectural principle.
13
+ Following SOLID principles—specifically the **Interface Segregation Principle (ISP)** and the **Dependency Inversion Principle (DIP)**—software components should depend on abstractions (interfaces), not on concrete logic.
14
+
15
+ While standard Python uses `abc.ABC` and `@abstractmethod` to enforce contracts, the syntax can often look cluttered, repetitive, and conceptually muddy (as Python abstract classes can accidentally mix actual logic with abstract models).
16
+
17
+ **`pyinterfaces`** bridges this gap by enforcing **Pure Interfaces**. It allows software engineers to declare strict structural contracts using the familiar, elegant, and universally understood Java/C# layout, keeping your architecture clean and highly readable.
18
+
19
+ ---
20
+
21
+ ## ✨ Features
22
+
23
+ - **Java-Style Syntax**: Declare structures using `Interface Name { ... }`.
24
+ - **Pure Abstraction**: No mixed implementation code allowed inside the contract block.
25
+ - **Runtime Enforcement**: Automatically triggers native Python `abc` validations under the hood.
26
+ - **Zero Overhead**: Translated seamlessly during file tokenization using custom stream decoding.
27
+
28
+ ---
29
+
30
+ ## 🚀 Installation
31
+
32
+ You can install `pyinterfaces` via `pip` or add it to your project using `poetry`:
33
+
34
+ ```bash
35
+ pip install pyinterfaces
36
+ ```
37
+
38
+ Or with Poetry:
39
+ ```bash
40
+ poetry add pyinterfaces
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 💻 Usage
46
+
47
+ To enable the custom Java-like syntax parsing, you **must** include the magic encoding comment `# -*- coding: java_interface -*-` at the very first line of your Python script.
48
+
49
+ Here is a standard example of designing a decoupled Payment System:
50
+
51
+ ```python
52
+ # -*- coding: java_interface -*-
53
+ import pyinterfaces
54
+
55
+ # 1. Define the pure architectural contract
56
+ Interface PaymentProcessor {
57
+ process_payment(self, amount: float) -> bool
58
+ refund_payment(self, transaction_id: str) -> None
59
+ }
60
+
61
+ # 2. Implement the contract in standard Python classes
62
+ class PixProcessor(PaymentProcessor):
63
+ def process_payment(self, amount: float) -> bool:
64
+ print(f"Processing R\${amount} instantly via Pix.")
65
+ return True
66
+
67
+ def refund_payment(self, transaction_id: str) -> None:
68
+ print(f"Refunding transaction {transaction_id}.")
69
+
70
+ # 3. Compile-time / Runtime validation
71
+ class BrokenProcessor(PaymentProcessor):
72
+ def process_payment(self, amount: float) -> bool:
73
+ return True
74
+ # ERROR! Missing 'refund_payment' method implementation.
75
+ ```
76
+
77
+ If a developer attempts to instantiate `BrokenProcessor`, Python will instantly raise a `TypeError`, stating that the class failed to implement the strict contract requirements defined by your interface.
78
+
79
+ ---
80
+
81
+ ## 🛠️ How it works under the hood
82
+
83
+ `pyinterfaces` hooks directly into Python's native `codecs` registry. When the interpretator reads the `# -*- coding: java_interface -*-` header, it streams your file through our custom pre-processor, safely transforming the custom block syntax into fully valid standard Python `abc.ABC` structures before the code even executes.
84
+
85
+ ---
86
+
87
+ ## 👤 Author
88
+
89
+ - Created and maintained by **Bruno Zolotareff**
90
+ - PyPI Repository: [https://pypi.org](https://pypi.org)
91
+
92
+ ## 🤝 Acknowledgments
93
+
94
+ Special thanks to my friend **Leandro Reginaldo** for collaborating on the original concept, brainstorming the architectural ideas, and helping to shape the vision of `pyinterfaces`. This project wouldn't be the same without your insights!
95
+
96
+
97
+ ## 📄 License
98
+
99
+ This project is licensed under the MIT License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ """
2
+ pyinterfaces - Java-style interfaces for Python.
3
+
4
+ Co-conceptualized and inspired by Leandro Reginaldo.
5
+ Maintained by Bruno Zolotareff.
6
+ """
7
+
8
+
9
+ from .compilador import registrar_syntax
10
+
11
+ # Ativa o mecanismo de codec assim que a biblioteca é importada
12
+ registrar_syntax()
@@ -0,0 +1,116 @@
1
+ import codecs
2
+ import io
3
+ import re
4
+
5
+ def converter_tipos_java_para_python(argumentos_str: str) -> str:
6
+ """
7
+ Transforma 'String titular, int idade' em 'titular: str, idade: int'.
8
+ Também garante que o 'self' seja mantido corretamente se o usuário colocar.
9
+ """
10
+ mapa_tipos = {
11
+ 'String': 'str',
12
+ 'int': 'int',
13
+ 'double': 'float',
14
+ 'float': 'float',
15
+ 'boolean': 'bool',
16
+ 'void': 'None',
17
+ 'List': 'list',
18
+ 'Map': 'dict'
19
+ }
20
+
21
+ argumentos_limpos = argumentos_str.strip()
22
+ if not argumentos_limpos:
23
+ return "self"
24
+
25
+ partes = [p.strip() for p in argumentos_limpos.split(',')]
26
+ novos_args = []
27
+
28
+ # CORREÇÃO AQUI: Verificamos se 'self' está contido na lista de partes
29
+ if len(partes) > 0 and partes[0] == 'self':
30
+ novos_args.append('self')
31
+ partes = partes[1:]
32
+ else:
33
+ # Injeta o 'self' automaticamente (padrão Java puro)
34
+ novos_args.append('self')
35
+
36
+ for parte in partes:
37
+ if not parte:
38
+ continue
39
+ componentes = re.split(r'\s+', parte)
40
+ if len(componentes) == 2:
41
+ tipo_java, nome_var = componentes
42
+ tipo_python = mapa_tipos.get(tipo_java, tipo_java)
43
+ novos_args.append(f"{nome_var}: {tipo_python}")
44
+ else:
45
+ novos_args.append(parte)
46
+
47
+ return ", ".join(novos_args)
48
+
49
+ def traduzir_sintaxe_java(texto: str) -> str:
50
+ """
51
+ Varre o arquivo de texto substituindo a sintaxe 'Interface Nome { ... }'
52
+ por classes Python puras usando abc.ABC, tipagem estrita e @abstractmethod.
53
+ """
54
+ linhas = texto.split('\n')
55
+ resultado = ["from abc import ABC, abstractmethod\n"]
56
+ dentro_da_interface = False
57
+
58
+ for linha in linhas:
59
+ # 1. Detecta o início da declaração: 'Interface Nome {'
60
+ inicio_match = re.match(r'\s*Interface\s+(\w+)\s*\{', linha)
61
+ if inicio_match:
62
+ nome_interface = inicio_match.group(1)
63
+ resultado.append(f"class {nome_interface}(ABC):")
64
+ dentro_da_interface = True
65
+ continue
66
+
67
+ if dentro_da_interface:
68
+ # 2. Detecta o fechamento da interface com a chave '}'
69
+ if '}' in linha:
70
+ dentro_da_interface = False
71
+ continue
72
+
73
+ # 3. Captura o método com padrão Java: TipoRetorno nomeMetodo(Argumentos)
74
+ linha_limpa = linha.strip().replace(';', '')
75
+ if linha_limpa:
76
+ metodo_match = re.match(r'(?:\w+\s+)?(\w+)\s*\((.*?)\)', linha_limpa)
77
+ if metodo_match:
78
+ nome_metodo = metodo_match.group(1)
79
+ args_brutos = metodo_match.group(2)
80
+
81
+ args_traduzidos = converter_tipos_java_para_python(args_brutos)
82
+
83
+ resultado.append(f" @abstractmethod")
84
+ resultado.append(f" def {nome_metodo}({args_traduzidos}):")
85
+ resultado.append(f" pass")
86
+ else:
87
+ resultado.append(linha)
88
+
89
+ return '\n'.join(resultado)
90
+
91
+ # --- INFRAESTRUTURA DE CODEC DO PYTHON ---
92
+
93
+ class JavaInterfaceDecoder(codecs.BufferedIncrementalDecoder):
94
+ def _buffer_decode(self, input, errors, final):
95
+ if final:
96
+ dados_em_bytes = bytes(input)
97
+ texto_traduzido = traduzir_sintaxe_java(dados_em_bytes.decode('utf-8'))
98
+ return (texto_traduzido, len(input))
99
+ return ('', 0)
100
+
101
+ def buscar_codec(nome_codec):
102
+ if nome_codec == 'py_interface':
103
+ return codecs.CodecInfo(
104
+ name='py_interface',
105
+ encode=codecs.utf_8_encode,
106
+ decode=lambda input, errors='strict': (traduzir_sintaxe_java(bytes(input).decode('utf-8')), len(input)),
107
+ incrementalencoder=codecs.utf_8_encode,
108
+ incrementaldecoder=JavaInterfaceDecoder,
109
+ streamreader=lambda stream, errors='strict': io.StringIO(traduzir_sintaxe_java(stream.read().decode('utf-8'))),
110
+ streamwriter=codecs.utf_8_encode
111
+ )
112
+ return None
113
+
114
+ def registrar_syntax():
115
+ """Registra o tradutor de código dentro do núcleo de encodings do Python"""
116
+ codecs.register(buscar_codec)
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "pyinterfaces"
3
+ version = "0.2.0"
4
+ description = "Interface in POO with Python"
5
+ authors = [
6
+ {name = "Bruno Zolotareff",email = "brunozolotareff@gmail.com"}
7
+ ]
8
+ readme = "README.md"
9
+ keywords = ["interface", "java", "syntax", "brunozolotareff", "pyinterfaces"]
10
+ packages = [{include = "pyinterfaces"}]
11
+ license = "MIT"
12
+ requires-python = ">=3.10"
13
+ dependencies = [
14
+ ]
15
+
16
+
17
+ [build-system]
18
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
19
+ build-backend = "poetry.core.masonry.api"
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "pytest (>=9.1.1,<10.0.0)"
24
+ ]
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pyinterfaces
3
- Version: 0.0.1
4
- Summary: Interface in POO with Python
5
- Author: Bruno Zolotareff
6
- Author-email: brunozolotareff@gmail.com
7
- Requires-Python: >=3.8
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.8
10
- Classifier: Programming Language :: Python :: 3.9
11
- Classifier: Programming Language :: Python :: 3.10
12
- Classifier: Programming Language :: Python :: 3.11
13
- Classifier: Programming Language :: Python :: 3.12
14
- Classifier: Programming Language :: Python :: 3.13
15
- Classifier: Programming Language :: Python :: 3.14
File without changes
@@ -1,16 +0,0 @@
1
- [project]
2
- name = "pyinterfaces"
3
- version = "0.0.1"
4
- description = "Interface in POO with Python"
5
- authors = [
6
- {name = "Bruno Zolotareff",email = "brunozolotareff@gmail.com"}
7
- ]
8
- license = ""
9
- requires-python = ">=3.8"
10
- dependencies = [
11
- ]
12
-
13
-
14
- [build-system]
15
- requires = ["poetry-core>=2.0.0,<3.0.0"]
16
- build-backend = "poetry.core.masonry.api"