Skip to content

Instantly share code, notes, and snippets.

@tenuki
Created February 20, 2014 17:03
Show Gist options
  • Save tenuki/9118509 to your computer and use it in GitHub Desktop.
Save tenuki/9118509 to your computer and use it in GitHub Desktop.
python use decimal as default type for non-integer numbers using macropy
# macro_module.py
from macropy.core.macros import *
from macropy.core.walkers import Walker
macros = Macros()
@macros.expr
def expand(tree, **kw):
return to_decimal(tree)
@macros.expr
def show(tree, **kw):
print tree
print real_repr(tree)
print unparse(tree)
return tree
@Walker
def w(tree, **kw):
is_num = tree.__class__==ast.Num
## if tree.__class__ == ast.Str:
## print 'got str'
if is_num and not isinstance(tree.n, int):
return to_decimal(convert_to_string(tree))
return tree
@macros.expr
def t(tree, **kw):
return w.recurse(tree)
def convert_to_string(a_num_node):
new_node = ast.Str()
new_node.col_offset = a_num_node.col_offset
new_node.lineno = a_num_node.lineno
# we should probable do something like:
# with open(source,'rb') as f:
# line = f.readlines()[a_num_node.lineno]
# i = a_num_node.col_offset
# while c[i] in '0123456789.':
# i++
# new_node.s = line[a_num_node.col_offset:i]
new_node.s = str(a_num_node.n)
return new_node
#Call(Name('Decimal', Load()), [Str('1.2')], [], None, None)
def to_decimal(tree):
return ast.Call(ast.Name('Decimal', ast.Load()),
[tree], [], None, None)
# run.py
import macropy.activate
import target
# target.py
from macro_module import macros, expand, show, t
from decimal import Decimal
def f(x):
return t[5.4]
print repr(f(None))
print f(None).__class__
@tenuki
Copy link
Author

tenuki commented Feb 20, 2014

TO DO / problems / questions / etc:

  1. is it possible to make a macro parse all the source instead of some "selection" ?
  2. is it possible to obtain the original value of ast.Num node instead of its already processed float?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment