How to modify function's locals before calling it in python - python-2.7

Suppose I have defined a function like this:
def calc():
print x
And I want to inject var x into the function's local by some ways before I calling it.
This looks like I added a keyword x and I can use x in function calc() without defining it. And what x will be is defined by the outer function who calls the calc().
Maybe this is a silly question, but I just want to know is it possible to do that?
If we can't modify it's locals before calling it, can we try another way? That is suppose we use decorator or something else to modify the func()'s definition automatically to
def clac(x):
print x
Maybe in this way, we need to play with the function's bytecode?
Can someone give some advise?

This seems like a very perverse thing to do, but it is actually possible. A reference to an undefined name compiles as a global variable reference, so we just need to call the function with a different global environment. Unfortunately, the func_globals attribute of functions is read-only, so we have to play some tricks with the function's code object. Try this:
exec calc.func_code in {'x': 'blah'}
Note that the dictionary you pass will be modified by adding a '__builtins__' slot - this allows the function to access Python's built-in functions and constants.

Related

What is dag in python? How is it used?

I am new to python, so bear with me. I see functions in python like below:
#dag.cellfn(dag.CanSet)
def XYZ(self):
return None
whats the purpose of such functions?
# denotes a decorator function. What this means is that before your XYZ function gets called, it will first call the dag.cellfn function with 2 arguments, a reference to XYZ and dag.CanSet. The decorated function (dag.cellfn) will do whatever it was written to do and eventually call the reference function (XYZ).
Decorators are often used to minimize code repetition, say you want to wrap every one of your functions with a try/catch. The decorator will let you write the try/catch once and then execute any function inside it.
You should read the python documentation for decorators.

Lua to c++, instanced functions for entity modification

I have been working on a simple component based c++ and lua game engine. Currently all the subsystems like audio and physics can be called from lua with there own module using luaL_newlib.
The problem I am having is how can a lua script call functions to modify its entity. Like SetPosition() is obviously going to need to be called on the instance of an entity rather than static functions. So is there a way I can have these instanced functions.
One idea I had was each entity registering functions for itself with a module name that is unique to it. So it would look like entity1.Setposition and entity2.Setposition. Would it be possible to register, effectively duplicate functions like this?
Or is there another way to have instanced functions like this so components can modify the entity that they are a part of?
If I have explained myself badly please do say so I will gladly provide more information
Lua has syntactic sugar for "instance methods." If you call a function with a colon instead of a dot, like this:
entity1:SetPosition(...)
then Lua rewrites it to this:
entity1.SetPosition(entity, ...)
In other words, it adds an implicit first argument which is the object that the method is being called on. On the C side, you just see an extra argument. This is the preferred way to make instance methods.
Two other noteworthy things: the rewrite above isn't exactly what happens. If you do something like this:
SomeFunctionReturningEntity():SetPosition(...)
it doesn't rewrite it to
SomeFunctionReturningEntity().SetPosition(SomeFunctionReturningEntity(), ...)
It actually just calls the function once, as you'd expect.
Also, if you're writing an instance method from Lua itself, not from C, there's syntactic sugar for declaring one:
function entity1:SetPosition(...)
end
This is equivalent to:
function entity1.SetPosition(self, ...)
end
i.e. it adds the implicit first argument to the function, and calls it self.
(Incidentally, that's also equivalent to this:
entity1.SetPosition = function(self, ...)
end
Technically, even declaring a function inside of a table is syntactic sugar.)

Custom bindings with boost::python [duplicate]

I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using boost.python to accomplish this.
Say there is a function defined in Python:
def callback(arg1, arg2):
#do something
return something
Now I need to pass this function to C++, so that it can be called from there. How do I write the code on C++ side using boost.python to achieve this?
If it might have any name:
Pass it to a function that takes a boost::python::object.
bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
pycb = cb;
}
If it is in a single known namespace with a consistent name:
bp::object pycb = bp::scope("namespace").attr("callback");
bp::object has operator() defined, so you call it just like any function
ret = pycb()
Not a clue. But you can use PyObject_Call() to call it once you have the function object.
I've not used it before, but the reference manual has a section called Calling Python Functions and Methods which seems to show how to do this.
I used PyRun_SimpleString("myFunction()") as quick hack, as my function's name was known, took no args and lived in the __main__ namespace. Note you additionally need to get lock GIL if you are multi-threaded.

GDB break on object function call

I'm debugging an issue, and I want to break on every method call that has a specific object as the 'this' parameter. Is this possible in GDB?
It's easy. You can use command like b A::a if (this==0x28ff1e).
The this parameter should only be the methods that are included in the class itself. So you should just need to set breakpoints for all Of the methods of the class you are looking at. I'm not sure there is a simple way to do that though.
I want to break on every method call that has a specific object as the 'this' parameter
This means that you want to break on every member function of a particular class for which the object has been instantiated.
Let's say for convenience that all the member functions are defined in a particular cpp file such as myclass_implementation.cpp
You can use gdb to apply breakpoint on every function inside myclass_implementation.cpp this way:
rbreak myclass_implementation.cpp:.
Let's say you want to break on some specific functions such as getter functions which start with Get, then you can use gdb to apply breakpoints this way:
rbreak myclass_implementation.cpp:Get*

changing llvm::Function signature after code generation, before last CreateRet

I'm trying to implement the following functionality;
a function with no explicit return will by default return the last evaluation in the last executed block
So, currently the process i'm doing is
1) create a Function
llvm::Function* result = llvm::Function::Create(Compiler::Detail::getAnonymousFunctionSignature(llvmContext),
llvm::GlobalValue::ExternalLinkage,
name,
module());
result->setCallingConv( llvm::CallingConv::C );
2) add blocks and evaluations to the blocks
builder.createFoo.....
However, only in the second phase i have the llvm::Value* (and compile-time type) that i want to use by default as return value. The problem is that i need to use this type to determine the signature of the created function
Question:
how do i solve the problem?
is possible to change the signature after the function is created? is it legal?
do i need to create a new function with the updated signature and copy/assign the entry block of the first function to it and thats it? or do i need to reevaluate all the expressions?
is possible to not create the function before code generation? if it is so, at what point should i create the function?
a code example of how to achieve this would be awesome. thanks!
You cannot change function signature, because this will mean that it will have different Type (and thus you will need to update all the users, etc.; this procedure in most cases cannot be done automagically).
There are multiple possible solutions, for example, you can create the function with the updated signature, then use the functions from lib/Transforms/Utils/CloneFunction.cpp to copy the function body and then hack on the return type.
A better solution exists than CloneFunctionInto(), according to https://stackoverflow.com/a/18751365/2024042:
NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
Where NF is the new function you're cloning into and F is the old function that you have just cloned.