package opine

  1. Overview
  2. Docs
Python AST unparse implementation in OCaml

Install

Dune Dependency

Authors

Maintainers

Sources

0.1.3.tar.gz
md5=21e2b1d21b779b2c53740663f34f98f3
sha512=16b28b7f7c476c378b08c2ac97b39c16f705374f74a98e2ba031c72aed1ae7388712754e9e9db976a867c84aa1878b214f9f467e40e33b16fa23355451fd3212

Description

Opine is an OCaml library that unparses the python AST back to python code.

Tags

topics ocaml python ast

Published: 23 Feb 2023

README

README.org

* Opine
Opine is an OCaml library that unparses the python AST produced by
pyre-ast library back to python source code.

** Why would this be useful?
I find this to be useful to do large scale python code transformations
in OCaml.

** Can this be done in Python itself?
Yes. But if you are looking for an OCaml library to do this, you
probably already know why you are looking. Maybe this will help. I
needed something like this to maintain python source code transformations.

** How it works?
Fairly simple. The pyre-ast module provides a concrete AST
representation of the python AST. The unparse module walks through the
ast recursively while maintaining some state information and converts
the AST back to python code. It doesn't use the visitor pattern.
Everything is pure, simple functions.

** Example transformation
If you wanted to add getters and setters to all the members in the
class
#+begin_src bash
dune exec examples -- module test.py
#+end_src
*** Input file
#+begin_src python
class Sample():
    def __init__(self, embed_dim, backend=None):
        self.embed_dim = embed_dim
        self.backend = backend
        
    def forward(self, weight, value):
        return torch.bmm(weight, value)
#+end_src
*** Output file
#+begin_src python
class Sample:
    def __init__(self, embed_dim, backend=None):
        self.embed_dim = embed_dim
        self.backend = backend

    def forward(self, weight, value):
        return torch.bmm(weight, value)

    @property
    def embed_dim(self):
        return self._embed_dim

    @property
    def backend(self):
        return self._backend

    @embed_dim.setter
    def embed_dim(self, embed_dim):
        self._embed_dim = embed_dim

    @backend.setter
    def backend(self, backend):
        self._backend = backend
#+end_src
** How to run the unparser?
 Pass a python file or module as input and have it generate the python
 ast and back.
 #+begin_src bash
 dune exec bin/main.exe -- module expr.py
 #+end_src

** Credits
This library exists because of [[https://github.com/grievejia/pyre-ast][pyre-ast]]

Dev Dependencies (1)

  1. odoc with-doc

Used by

None

Conflicts

None

OCaml

Innovation. Community. Security.