Cause syntax error when assigning to 'var - #39
Conversation
Hey, thanks for the PR. It's an interesting idea. I think it would be nicer to make the Rust globals an object with read-only properties. One downside for that is that it gives a runtime error when trying to assign, rather than syntax errors. But it's python, so I think people will forgive that. The advantage is that the error message will make more sense, and there's no need to intercept and adjust error messages then. |
My first Idea was to use a new type as classReadOnlyRustVariables:
def__init__(self, dict):
self.dict=dictdef__getitem__(self, key):
returnself.dict[key]
def__setitem__(self, key, val):
ifkey.startswith("__rust_var_"):
k=key[len("__rust_var_"):]
raiseTypeError(f"You can not modify the rust-variable '{k} use Context::get_global()")
self.dict[key] =vallocals_=ReadOnlyRustVariables({"__rust_var_x":42})
globals_=vars(__import__("builtins"))
exec("y = __rust_var_x * 2", globals_, locals_)
assertlocals_["y"] ==84, locals_exec("__rust_var_x = __rust_var_x * 2", globals_, locals_)
# TypeError: You can not modify the rust-variable 'x use Context::get_global()I didn't try this one. another Idea was to replace classRustVars: __slots__= ("_dict", "_mutable") def__init__(self, mutable:bool): self._dict=dict() self._mutable=mutabledef__setitem__(self, key, value): ifself._mutable: self._dict[key] =valueelse: raiseTypeError("You are trying to write to "+'\''+key+" which is read-only. Try #"+key) def__getitem__(self, key): returnself._dict[key] _RUST_MUT_VARS=RustVars(True) _RUST_IMMUT_VARS=RustVars(False) delRustVarsfrombuiltinsimport*I tried implementing the second in rust and failed to run python code when initializing the context. When I thought of the lambda trick and found it easy to implement I liked the compile time errors better than runtime errors, even if the Error Message is not perfect. |
8ec0e98 to
635617fCompare
You can cause a Syntaxerror for assignments to rust variables by expanding them to
((lambda:_RUST_var)())Since the SyntaxError has a very confusing message, the likely cause is appended:
The Error message could be improved by inspecting the code it is raised for, but I don't know how to do it reliably.