Skip to content

Instantly share code, notes, and snippets.

@stuartmyles
Created August 9, 2015 21:46
Show Gist options
  • Save stuartmyles/dd5283ec2fafd80d8470 to your computer and use it in GitHub Desktop.
Save stuartmyles/dd5283ec2fafd80d8470 to your computer and use it in GitHub Desktop.
Python ast code to call an instance object method and pass in a parameter, i.e. equivalent to result = self._baz(theResult)"
import ast
# ast code to call an instance object method and pass in a parameter, i.e. equivalent to
# result = self._baz(theResult)"
class Greeter:
def _baz(self, theStr):
return theStr
def baz(self, theResult):
assignresult = ast.Module(body=[ ast.Assign(targets = [
ast.Name(id = 'result', ctx = ast.Store())],
value =
ast.Call(func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), attr='_baz', ctx=ast.Load()),
ctx=ast.Load(),
args=[ast.Name(id="theResult", ctx=ast.Load())],
keywords=[]))
])
ast.fix_missing_locations(assignresult)
co = compile(assignresult, "<ast>", "exec")
exec(co)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment