Created
February 20, 2014 17:03
-
-
Save tenuki/9118509 to your computer and use it in GitHub Desktop.
python use decimal as default type for non-integer numbers using macropy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # run.py | |
| import macropy.activate | |
| import target |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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__ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TO DO / problems / questions / etc: