This package is dedicated to parse and work with various languages, in particular Python itself and ABCD. These are mainly utilities for internal use in SNAKES, however, they may be of general interest independently of SNAKES.
Module ast
The module ast
exported by snakes.lang
is similar to Python's
standard ast
module (starting from version 2.6) but is available and
uniform on every implementation of Python supported by SNAKES: CPython
from 2.5, Jython and PyPy. (In general, these modules are available in
these implementation - except CPython 2.5 - but with slight
differences, so using snakes.lang.ast
can be seen as a portable
implementation.)
Notice that this module is not available for direct import but is
exposed as a member of snakes.lang
. Moreover, when snakes.lang
is
loaded, this module ast
is also loaded as snkast
in sys.modules
,
this allows to have both versions from Python and SNAKES
simultaneously.
>>> import snakes.lang.ast as ast
ImportError ...
...
ImportError: No module named ast
>>> from snakes.lang import ast
>>> import snkast
Function getvars
def getvars (expr) :
Return the set of variables (or names in general) involved in a Python expression.
>>> list(sorted(getvars('x+y<z')))
['x', 'y', 'z']
>>> list(sorted(getvars('x+y<z+f(3,t)')))
['f', 't', 'x', 'y', 'z']
Call API
str expr
: a Python expressionreturn set
: the set of variable names as strings
Function rename
def rename (expr, map={}, **ren) :
Rename variables (ie, names) in a Python expression
>>> rename('x+y<z', x='t')
'((t + y) < z)'
>>> rename('x+y<z+f(3,t)', f='g', t='z', z='t')
'((x + y) < (t + g(3, z)))'
>>> rename('[x+y for x in range(3)]', x='z')
'[(x + y) for x in range(3)]'
>>> rename('[x+y for x in range(3)]', y='z')
'[(x + z) for x in range(3)]'
Call API
str expr
: a Python expressiondict map
: a mapping from old to new names (str
tostr
)str ren
: additional mapping of old to new namesreturn str
: the new expression
Function bind
def bind (expr, map={}, **ren) :
Replace variables (ie, names) in an expression with other
expressions. The replacements should be provided as ast
nodes,
and so could be arbitrary expression.
>>> bind('x+y<z', x=ast.Num(n=2))
'((2 + y) < z)'
>>> bind('x+y<z', y=ast.Num(n=2))
'((x + 2) < z)'
>>> bind('[x+y for x in range(3)]', x=ast.Num(n=2))
'[(x + y) for x in range(3)]'
>>> bind('[x+y for x in range(3)]', y=ast.Num(n=2))
'[(x + 2) for x in range(3)]'
Call API
str expr
: a Python expressiondict map
: a mapping from old to new names (str
toast.AST
)ast.AST ren
: additional mapping of old to new namesreturn str
: the new expression