RedBaron – a bottom up approach to refactoring in python (Laurent Peuch)

Refatoring code = rewriting it without changing its behaviour.

Refactoring generally works on the Abstract Syntax Tree (AST).

Often in your code you see some pattern that you would like to change, but it’s more complicated than the simple refactorings typically provided (rename, inline, move, …). So you’d like to write your own refactoring. Also code generation is often useful. There are only a few people in the world who do that kind of thing.

Ast.py has tthreewo problems. It looses information: comments, formatting is removed. Also it is not (officially) possible to go back to source code. And finally its API is SAX-like which doesn’t make it easy to work with. So, we miss a good abstraction and a good API.

Baron is a lossless AST for python. So code manipulation becomes graph manipulation instead of string analysis. It gives a bit of abstraction above the text, but nothing spectacular yet.

RedBaron is the API that makes working with the AST easy and fun. Like BeautifulSoup, it maps a data structure to objects. It tries to do all the boring lowlevel stuff for you. When you print a node from the AST, it just dumps the corresponding source code with the index of each subnode indicated. Also, .help() tells you which things you can do with it. .find() looks for a subnode of a certain type or matching a filter.

To modify a node, just assign a string to it. RedBarron will reparse that in re-inject it. It magically re-indents where needed. Similar for lists.

With RedBaron it becomes really easy to do relatively simple changes to your code. It should work for about 80% of the cases.

There is no static analysis. For that, look at astroid/jedi.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s