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.
Related
I try to figure out the meaning of decorator in python, and practice a snippet as below on python console:
def print_my_name(name):
print "I am %s" %(name())
#print_my_name
def my_name():
return "Hans"
And it will come out with,
I am Hans
It never happens on normal functions.
Could anybody tell me how it works?
Thank you
A decorator takes the function definition and creates a new function that executes this function and transforms the result.
The shortest explanation that I can give is that decorators wrap your function in another function that returns a function.
This code, for example:
#decorate
def foo(a):
print a
would be equivalent to this code if you remove the decorator syntax:
def bar(a):
print a
foo = decorate(bar)
Decorators sometimes take parameters, which are passed to the dynamically generated functions to alter their output.
Another term you should read up on is closure, as that is the concept that allows decorators to work.
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.
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.)
I have this view function search(request). The url suffix is /search. It takes a few POST parameters and shows search results accordingly.
I want to make a second function show_popular(request). It takes no post or get parameters. But it should emulate a call to the search function with some hard coded post parameters.
I want to achieve this without changing anything in any existing function and without changing setup. Is that possible?
EDIT: I know this can be achieved by refactoring the search into a separate function and have several view functions call this. But in this particular case, I am not interested in that. In my case the show_popular function is only temporary, and for irrelevant reasons I do not wish to re-factor.
Yes, but you don't want to do that. Refactor search() into a function that handles the request and a function that performs the search, and call the latter from show_popular().
I'd like some advice on how to check for the correctness of the parameters I receive.
The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should have to ensure that it meets the criteria.
So...
How do you check that an object is a function?
How do you check that an object is a bound method?
How do you check that an object is a class object?
How do you check that a class object is a child of another class?
When in doubt just work out how you would get the required effect by calling the usual Python builtins and translate it to C/C++. I'll just answer for Python, for C you would look up the global such as 'callable' and then call it like any other Python function.
Why would you care about it being a function rather than any other sort of callable? If you want you can find out if it is callable by using the builtin callable(f) but of course that won't tell you which arguments you need to pass when calling it. The best thing here is usually just to call it and see what happens.
isinstance(f, types.MethodType) but that won't help if it's a method of a builtin. Since there's no difference in how you call a function or a bound method you probably just want to check if it is callable as above.
isinstance(someclass, type) Note that this will include builtin types.
issubclass(someclass, baseclass)
I have two unconventional recommendations for you:
1) Don't check. The Python culture is to simply use objects as you need to, and if it doesn't work, then an exception will occur. Checking ahead of time adds overhead, and potentially limits how people can use your code because you're checking more strictly than you need to.
2) Don't check in C++. When combining Python and C (or C++), I recommend only doing things in C++ that need to be done there. Everything else should be done in Python. So check your parameters in a Python wrapper function, and then call an unchecked C++ entry point.