-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow type hinting #219
Comments
mohankumaru wrote at 2022-1-19 02:13 -0800:
Is there a way to include annotated assignment in the code being executed?
Currently, this is not possible.
...
Where I am looking to add type hints to my inline code "sample_code". It will throw saying " AnnAssign statements are not allowed.". Is there a way to get around this?
Why is this important for you?
Those annotations are hints only; you need external tools to make
effective use of them.
`RestrictedPython` works by compiling the source first into
an "AST" (= "Abstract Syntax Tree") in the normal way and
then use an AST transformation to check constructs at runtime
(that's where not explicitly supported features such as annotations
are rejected) and transform (some) other constructs to make runtime checks
possible.
You can either monkey patch the transformation class
or derive your own transformation class to allow annotations.
But I wonder if it is worth the effort.
|
|
Currently not supporting does not mean: will never support. So I am reopening this issue and mark it as an enhancement request. As type annotations do not influence the runtime behavior it should be no problem to support them during the parsing and remove them from the AST. |
Hi I stumbled upon this issue and wanted to add that this is trivial to implement because User code could look like this from RestrictedPython import RestrictingNodeTransformer
class MyNodeTransformer(RestrictingNodeTransformer):
def visit_AnnAssign(self, node: AnnAssign) -> Any:
return self.node_contents_visit(node) Here's our implementation: https://github.com/onecommons/unfurl/blob/c238d00e916d7071191104dd3fab0a34aded2574/tosca-package/tosca/loader.py#L504 In Python 3.12, the following node types were added for the new type alias syntax, so you might want to add these too, they only impact type annotations so are safe at runtime: def visit_TypeAlias(self, node) -> Any:
return self.node_contents_visit(node)
def visit_TypeVar(self, node) -> Any:
return self.node_contents_visit(node)
def visit_TypeVarTuple(self, node) -> Any:
return self.node_contents_visit(node)
def visit_ParamSpec(self, node) -> Any:
return self.node_contents_visit(node) |
Hi,
Is there a way to include annotated assignment in the code being executed?
Where I am looking to add type hints to my inline code "sample_code". It will throw exception saying " AnnAssign statements are not allowed.". Is there a way to get around this?
The text was updated successfully, but these errors were encountered: