11. Exercício prático: Versão 3

Esta nova versão introduz duas alterações:
- os dados necessários para calcular o imposto, fornecidos pela autoridade fiscal, são armazenados num ficheiro JSON [admindata.json]:
{
"limites": [9964, 27519, 73779, 156244, 0],
"coeffR": [0, 0.14, 0.3, 0.41, 0.45],
"coeffN": [0, 1394.96, 5798, 13913.69, 20163.45],
"PLAFOND_QF_DEMI_PART": 1551,
"PLAFOND_REVENUS_CELIBATAIRE_POUR_REDUCTION": 21037,
"PLAFOND_REVENUS_COUPLE_POUR_REDUCTION": 42074,
"VALEUR_REDUC_DEMI_PART": 3797,
"PLAFOND_DECOTE_CELIBATAIRE": 1196,
"PLAFOND_DECOTE_COUPLE": 1970,
"PLAFOND_IMPOT_COUPLE_POUR_DECOTE": 2627,
"PLAFOND_IMPOT_CELIBATAIRE_POUR_DECOTE": 1595,
"ABATTEMENT_DIXPOURCENT_MAX": 12502,
"ABATTEMENT_DIXPOURCENT_MIN": 437
}
- Os resultados do cálculo do imposto também serão colocados num ficheiro JSON [results.json]:
[
{
"marié": "oui",
"enfants": 2,
"salaire": 55555,
"impôt": 2814,
"surcôte": 0,
"décôte": 0,
"réduction": 0,
"taux": 0.14
},
{
"marié": "oui",
"enfants": 2,
"salaire": 50000,
"impôt": 1384,
"surcôte": 0,
"décôte": 384,
"réduction": 347,
"taux": 0.14
},
…
{
"marié": "oui",
"enfants": 3,
"salaire": 200000,
"impôt": 42842,
"surcôte": 17283,
"décôte": 0,
"réduction": 0,
"taux": 0.41
}
]
11.1. O script de configuração [config.py]
O script de configuração será o seguinte:
| def configure():
import os
# absolute path of this script's folder
script_dir = os.path.dirname(os.path.abspath(__file__))
# application dependencies
absolute_dependencies = [
f"{script_dir}/../shared",
]
# application configuration
config = {
# absolute path of the taxpayer file
"taxpayersFilename": f"{script_dir}/../data/taxpayersdata.txt",
# absolute path of the results file
"resultsFilename": f"{script_dir}/../data/résultats.json",
# absolute path of tax administration data file
"admindataFilename": f"{script_dir}/../data/admindata.json"
}
# update syspath
from myutils import set_syspath
set_syspath(absolute_dependencies)
# return the config
return config
|
- Linha 8: Adicione a pasta [shared] ao Python Path. Esta pasta contém o módulo [impôts_module_02] utilizado pelo script principal;
11.2. Script principal [main.py]
O script principal para a versão 3 é o seguinte:
| # configure the application
import config
config = config.configure()
# syspath is configured - imports can be made
from impôts_module_02 import calcul_impôt, get_admindata, get_taxpayers_data, record_results_in_json_file
# taxpayer file
taxpayers_filename = config['taxpayersFilename']
# results file
results_filename = config['resultsFilename']
# tax administration data file
admindata_filename = config['admindataFilename']
# code
try:
# reading tax administration data
admindata = get_admindata(admindata_filename)
# reading taxpayer data
taxpayers = get_taxpayers_data(taxpayers_filename)
# results list
results = []
# taxpayers' taxes are calculated
for taxpayer in taxpayers:
# tax calculation returns a dictionary of keys
# ['married', 'children', 'salary', 'tax', 'surcôte', 'décôte', 'réduction', 'taux']
result = calcul_impôt(admindata, taxpayer['marié'], taxpayer['enfants'], taxpayer['salaire'])
# the dictionary is added to the list of results
results.append(result)
# we record the results
record_results_in_json_file(results_filename, results)
except BaseException as erreur:
# there may be various errors: no file, incorrect file content
# display the error and exit the application
print(f"L'erreur suivante s'est produite : {erreur}]\n")
finally:
print("Travail terminé...")
|
Notas
- Linhas 2–4: Configuramos a aplicação, especificamente o seu caminho Python;
- linha 7: importamos as funções de que precisamos para [main.py];
- Linhas 9–14: Os nomes dos ficheiros utilizados pela aplicação são recuperados da configuração;
- O script principal na versão 3 apresenta três diferenças em relação às versões 1 e 2:
- linha 21: os dados da autoridade fiscal são recuperados do ficheiro JSON [./data/admindata.json];
- linha 32: os resultados do cálculo de impostos são colocados no ficheiro JSON [./data/results.json];
- linha 7: as funções na versão 3 estão localizadas no módulo [impots.modules.impôts_module_02];
11.3. O módulo [impots.v02.modules.impôts_module_02]
O módulo [impots.v02.modules.impôts_module_02] tem a seguinte estrutura:

- O módulo contém funções já presentes no módulo utilizado pela versão 1, com uma diferença. Quando o módulo da versão 2 reutiliza uma função do módulo da versão 1, fá-lo com um parâmetro adicional: [adminData] (linhas 29, 51, 77, 127). Este parâmetro representa o dicionário de dados fiscais do ficheiro JSON [adminData.json]. No módulo da Versão 1, estes dados não precisavam de ser passados para as funções porque estavam definidos globalmente para elas, o que significa que as funções já os conheciam;
11.4. Leitura de dados da administração fiscal
A função [get_admindata] é a seguinte:
| # read data from tax authorities in a jSON file
# ----------------------------------------
def get_admindata(admindata_filename: str) -> dict:
# reading tax administration data
# we let any exceptions go up: file missing, jSON content incorrect
file = None
try:
# open file jSON in read mode
file = codecs.open(admindata_filename, "r", "utf8")
# transfer content to a dictionary
admin_data = json.load(file)
# we return the result
return admin_data
finally:
# close the file if it has been opened
if file:
file.close()
|
- linha 9: recuperar o dicionário de imagens do ficheiro JSON lido;
11.5. Guardar os resultados
A função [record_results_in_json_file] é a seguinte:
| # writing results to a jSON file
# ----------------------------------------
def record_results_in_json_file(results_filename: str, results: list):
file = None
try:
# opening the results file
file = codecs.open(results_filename, "w", "utf8")
# block writing
json.dump(results, file, ensure_ascii=False)
finally:
# close the file if it has been opened
if file:
file.close()
|
- linha 7: criar um ficheiro codificado em UTF-8;
- linha 9: escreve a lista [results] no ficheiro JSON. Os caracteres UTF-8 não são escapados (ensure_ascii=False);
11.6. Alterações nas funções
Algumas funções recebem agora um parâmetro adicional [admin_data]. Isto altera ligeiramente a sua sintaxe. Veja-se, por exemplo, a função [calcul_impôt]:
| # tax calculation - step 1
# ----------------------------------------
def calcul_impôt(admin_data: dict, marié: str, enfants: int, salaire: int) -> dict:
# married: yes, no
# children: number of children
# salary: annual salary
# limits, coeffr, coeffn: data tables for tax calculation
#
# tax calculation with children
result1 = calcul_impôt_2(admin_data, marié, enfants, salaire)
impot1 = result1["impôt"]
# tax calculation without children
if enfants != 0:
result2 = calcul_impôt_2(admin_data, marié, 0, salaire)
impot2 = result2["impôt"]
# application of the family allowance ceiling
if enfants < 3:
# PLAFOND_QF_DEMI_PART euros for the first 2 children
impot2 = impot2 - enfants * admin_data['plafond_qf_demi_part']
else:
# PLAFOND_QF_DEMI_PART euros for the first 2 children, double for subsequent children
impot2 = impot2 - 2 * admin_data['plafond_qf_demi_part'] - (enfants - 2) * 2 * admin_data[
'plafond_qf_demi_part']
else:
impot2 = impot1
result2 = result1
# we take the highest tax with the rate and surcharge that go with it
if impot1 > impot2:
impot = impot1
taux = result1["taux"]
surcôte = result1["surcôte"]
else:
surcôte = impot2 - impot1 + result2["surcôte"]
impot = impot2
taux = result2["taux"]
# calculation of any discount
décôte = get_décôte(admin_data, marié, salaire, impot)
impot -= décôte
# calculation of any tax reduction
réduction = get_réduction(admin_data, marié, salaire, enfants, impot)
impot -= réduction
# result
return {"marié": marié, "enfants": enfants, "salaire": salaire, "impôt": math.floor(impot), "surcôte": surcôte,
"décôte": décôte, "réduction": réduction, "taux": taux}
|
Notas
- sempre que [calcul_tax] chama outras funções, passa [admin_data] como primeiro parâmetro (linhas 10, 14, 39, 42);
- onde [tax_calculation] utiliza constantes fiscais, agora acede às mesmas através do dicionário [admin_data] (linhas 19, 22);
Todas as funções que recebem [admin_data] como parâmetro sofrem este mesmo tipo de alterações.
11.7. Resultados
Os resultados obtidos são os apresentados no início da Secção 8.3.