Invoking return through a function?
Alberto Berti
alberto at metapensiero.it
Tue Oct 31 07:54:30 EDT 2017
>>>>> "Lele" == Lele Gaifax <lele at metapensiero.it> writes:
Lele> ram at zedat.fu-berlin.de (Stefan Ram) writes:
Stefan> There are many macro processors available, like the C macro
Stefan> preprocessor, gpp, M4, or funnelweb. You can always use them
Stefan> for your Python source (which, in this case, isn't exactly Python
Stefan> source anymore).
Lele> Even more to the point, MacroPy! See https://github.com/azazel75/macropy for a
Lele> 3.5+ version.
I share the opinion of Stefan and others, it's a bad practice. But just
to have some fun I implemented it with MacroPy...
This is the module with the test code::
# test.py
from test_macros import macros, check_macro
def checkKey(k, m):
return k in m
@check_macro
def test():
m = {1: 'a', 2: 'b'}
print('before')
checkKey(3, m)
print('after')
here the test function is wrapped by the macro, that is defined as:
# test_macros.py
from macropy.core.macros import Macros
from macropy.core.quotes import macros, q, u, ast_literal
from macropy.core.walkers import Walker
from macropy.experimental.pattern import macros, switch, _matching, ClassMatcher
from ast import Call, Name, Expr
macros = Macros()
@macros.decorator
def check_macro(tree, **kw):
@Walker
def transform_checkKey(tree, stop, **kw):
with switch(tree):
if Expr(value=Call(func=Name(id='checkKey'))):
with q as result:
if not ast_literal[tree.value]:
print('exiting!')
return
stop()
else:
result = tree
return result
return transform_checkKey.recurse(tree)
The macro is run with all the decorated code of the ``test()`` method
passed as the ``tree`` parameter in the form of ast tree. A tree walker
is then run to navigate the tree and augment the occurrence of checkKey
with the conditional return
And finally, a ``main`` module is needed to activate macro parsing and
substitution:
# test_main.py
import macropy.activate
import test
test.test()
cheers,
Alberto
More information about the Python-list
mailing list