Implementing Variables class + dump and trace
This commit is contained in:
68
modules/Variables.py
Normal file
68
modules/Variables.py
Normal file
@ -0,0 +1,68 @@
|
||||
import sys
|
||||
|
||||
trace_format = '\033[1m -> '
|
||||
reset_format = '\033[0m'
|
||||
|
||||
class Variables:
|
||||
|
||||
class Variable:
|
||||
types = { "entier": int,
|
||||
"texte": str,
|
||||
"booléen": bool,
|
||||
"liste": list }
|
||||
|
||||
def __init__(self, typ, value = None):
|
||||
assert typ in self.types.keys(), "Ce type de variable est inconnu"
|
||||
self.type = typ
|
||||
assert self.checkType(value, typ), "Le type n'est pas équivalent"
|
||||
self.value = value if (value is not None) else self.default(typ)
|
||||
|
||||
def set(self, value):
|
||||
assert self.checkType(value, self.type), "Le type n'est pas équivalent"
|
||||
self.value = value
|
||||
|
||||
def __str__(self):
|
||||
if self.type == "booléen":
|
||||
return "Vrai" if self.value else "Faux"
|
||||
return f"{self.value}"
|
||||
|
||||
def __repr__(self):
|
||||
if self.type == "texte":
|
||||
return f"\"{self.value}\""
|
||||
return f"{self.value}"
|
||||
|
||||
|
||||
def checkType(self, value, typ) -> bool:
|
||||
return type(value) == self.types[typ]
|
||||
|
||||
def default(self, typ):
|
||||
if typ == "entier":
|
||||
return 0
|
||||
if typ == "texte":
|
||||
return ""
|
||||
if typ == "booléen":
|
||||
return False
|
||||
if typ == "liste":
|
||||
return []
|
||||
|
||||
def __init__(self, trace=False):
|
||||
self.variables = {}
|
||||
self.trace = trace
|
||||
|
||||
def get(self, name):
|
||||
assert name in self.variables, "la variable {name} n'éxiste pas"
|
||||
if self.trace:
|
||||
print(f"{trace_format}accède {name}{reset_format}", file=sys.stdout)
|
||||
return self.variables[name]
|
||||
|
||||
def declare(self, typ, name, value=None):
|
||||
assert name not in self.variables, "la variable {name} existe déjà"
|
||||
self.variables[name] = self.Variable(typ, value)
|
||||
if self.trace:
|
||||
print(f"{trace_format}déclare {name} = {value}{reset_format}", file=sys.stdout)
|
||||
|
||||
def assign(self, name, value):
|
||||
assert name in self.variables, "la variable n'éxiste pas"
|
||||
self.variables[name].set(value)
|
||||
if self.trace:
|
||||
print(f"{trace_format}modifie {name} = {value}{reset_format}", file=sys.stdout)
|
BIN
modules/__pycache__/Variables.cpython-313.pyc
Normal file
BIN
modules/__pycache__/Variables.cpython-313.pyc
Normal file
Binary file not shown.
Reference in New Issue
Block a user