I have a tuple like the following:
self.tagnames = (('string', self.do_anything()),)
It should execute a specific function if a string matches to another.
However, when I initialize self.tagnames, it seems to execute the function already.
How can I fix my issue without executing the function on startup?
self.tagnames = (('string', self.do_anything),)
The () is a function call. If you want to defer the call until later, and just include the function reference without the parens like so.
self.tagnames = (('string', self.do_anything),)
You invoke a function by using parens with an argument list:
len is a function, len(s) is invoking that function on the argument s. Simply using the function's name gets you the function. Leave off the parenthesized argument list, and you are no longer invoking the function.
You should just remove the parenthesis:
self.tagnames = (('string', self.do_anything),)
Clearly self.do_anything() calls the method immediately, instead self.do_anything returns what in Python is called a "bound method", i.e. it's a callable object to which you can pass just the parameters (if any) and that will result in calling the method on the specific instance.
Related
So I came across this but don't fully understand why this is the case:
count = 0
Got_one = 0
while(count<1):
print('\n')
response = input("Did you get one?\n:").lower()#<--This part here
if response == 'yes':
Got_one += 1
#...ect
At one point of the script I had typed up .lower without the (). The code ran fine but the script failed to +1 when I inputted "yes", instead it printed out a value of 0, most likely due to the "Got_one" variable being set to 0 in the very beginning. However, as soon as I typed up the () the code worked as intended and +1 to the value after inputting "yes".
So, why is this the case? Is .lower on its own lowering everything after it or just something I don't understand about Python yet?
.lower() is a built-in method for the String object in Python. The reason you need the parenthesis is to execute the function on the string.
Without the parenthesis, you are simply accessing the String.lower attribute, which is a function pointer. Therefore, without the parenthesis, you are setting response = String.lower, which will not pass the if statement.
the difference is that calling it with no parenthesis is your just calling the method but not the value of that method and calling it with parenthesis your calling the value of that method
The reason for that is because .lower() is a class method, not a class attribute (which would be written as .lower).
Therefore, you have to use parenthesis to indicate that you are trying to call a method.
Since it does not take any arguments, you simply only put empty parenthesis behind it.
A class method is a function that belongs to a class object, in this case a str object.
A class attribute is a variable that belongs to this object.
To add to 1313e's answer, .lower() is actually a built-in method (functions for object classes) that you're performing on the string object (because everything in Python is an object), which is why you call 'this string'.lower() and not, say, lower('this string')
This is because you are merely making a reference to the lower class method (function) of the class object str. For reference:
foo = "ALL CAPS"
bar = foo.lower
bar
>>> <built-in method lower of str object at 0x1038e1570>
bar()
>>> 'all caps'
I am trying to construct a dispatch the following way:
def run_nn(type=None):
print type, 'nn'
return
def run_svm(type=None):
print type, 'svm'
return
action = {'nn' : run_nn( type=None),
'svm' : run_svm(type=None),}
I want the function to be executed only when called with something like:
action.get('nn',type='foo')
With expectation it to print:
foo nn
But it breaks giving:
TypeError: get() takes no keyword arguments
What's the right way to do it?
Furthermore, two functions run_nn() and run_svm() were executed without even being called. I don't want that. How can I avoid it?
You're calling the functions while building the dictionary. You should instead put the function objects in the dict without calling them. And afterwards, get the appropriate function from the dict and call it with the keyword argument.
What you want is:
action = {'nn' : run_nn,
'svm' : run_svm,}
...
action.get('nn')(type='foo') # get function object from dict and then call it.
I'll suggest you use action['nn'] over action.get('nn') since you're not specifying any default callable in the get method; the get method returns None when you don't specify one. A KeyError is much more intuitive than a TypeError NoneType object is not callable in this scenario.
On another note, you can drop those return statements as you aren't actually returning anything. Your function will still return without them.
BTW, I have the feeling your function(s) want to change behavior depending on type (although your type is counter-intuitive as it is always a string). In any case, you may have a look at functools.singledispatch. That'll transform your function(s) into a single-dispatch generic function with the possibility to create several overloaded implementations.
Finally, although type does make for a good argument name, you will run into problems when you need to use the builtin type in your function.
In the Beaker documentation, they talk about not passing a parameter directly in the createfunc call but use a closure.
The creation function must not accept any arguments as it won’t be called with any. Options affecting the created value can be passed in by using closure scope on the creation function:
All examples and documentation I can find on closure hint toward a nested function call with the first taking in a variable. In this case I don't understand how to write the closure since its not a function but a key value variable.
results = tmpl_cache.get(key=search_param, createfunc=get_results)
How would I pass variable_a into get_results(variable_a) in the createfunc?
Like so, or similar?
get_results_func returns a function pointer that, because it's in a closure, will call get_results correctly.
def get_results_func(variable_a):
def call_get_results():
return get_results(variable_a)
return call_get_results # note the absence of brackets here.
results = tmpl_cache.get(key=search_param, createfunc=get_results_func(variable_a))
I just want to know if there is some way in Python to make function and its arguments from the list and store them in a variable that can be passed to eval
e.g. :
def dummyfunction(title):
print "Hello %s" %(title)
Normal way to invoke this function is :
dummyfunction("John")
I am having the function name and its arguments inside the list as list1 = ['dummyfunction', 'John'].My requirement is to get a string representation of this function as dummyfunction("John") which can be used as an input to eval function since it takes string argument.
First of all, if you can, instead of putting the name of the function, just put the function itself in a list:
sexpression = [dummyfunction,1,2,3]
sexpression[0](*sexpression[1:])
If the function is an object method, then you can use getattr:
strpression = ['dummyfunction',1,2,3]
getattr(myobj,strpression[0])(*strpression[1:])
If it's in a known module, you can do the exact same thing with the module object in place of myobj
Because you can look up a function by name, there is no reason to ever use eval to call a function. Don't do it.
Finally, if you want to collect arbitrary functions together for lookup by name you can do:
namespace = {'dummyfunction': dummyfunction}
#or
namespace = {f.__name__:f for f in [dummyfunction]}
If the function is defined as module global, you can use globals:
func = globals()[list1[0]]
func(list1[1])
But above code could cause any abitrary function to be called. If you don't want that, use following form.
funcs = {
'dummyfunction': dummyfunction,
}
func = funcs[list1[0]]
func(list1[1])
if you just wanted a string representation of the function call to pass into eval then you can do this:
eval("dummyFunction(\"John\")")
#or
eval("dummyFunction('John')")
if you had a list with function name and argument then do this:
list1 = ['dummyfunction', 'John']
eval(list1[0]+"('"+list1[1]+"')")
Is the first reference in the list really the string name of the function, or is it the function object itself? If it's the function object itself, you can do this:
list[0](*list[1:])
If it's really the string name, you can try:
globals()[list[0]](*list[1:])
Note that this will only work if your function is defined in the global namespace. If it's in a local namespace, or a class or something, then you'll need to get the function from that namespace, instead of globals().
I am a newbie to Python, i am having some doubts on working of below mentioned code snippet from shutil module.
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
When a call to shutil.copytree is made with ignore option set to ignore_patterns, then it calls ignore_patterns function and returns a function. My doubts are:
1) ignore_patterns when called will return the _ignore_pattern function reference. Now when this function will be called, how is it still accessing the "patterns" list? Once called function "ignore_patterns" has returned, list patterns which was created at its call should be available for its called scope only.
2) What is the signicance of underscore in the returned function _ignore_patterns function name?
This is called a closure, and it's a general feature of languages that allow nested functions. Inner functions can close over variables in an outer scope, and will retain a reference to that name when they are called from outside the outer function.
The underscore is just to signify that _ignore_patterns is an inner function, while keeping the name of the returned function similar. It could be called anything you like.
ignore_patterns when called will return _ignore_pattern function reference. Now when this function will be called, how it is still accessing the "patterns" list.
This is fine. _ignore_pattern is a closure. That means it keeps around all the local variables (including function parameters) that it needs to do its job. Eventually the garbage collector will get it, but not while it might still be needed.
What is the signicance of underscore in returned function _ignore_patterns function name?
The author just wanted to disambiguate the names. It beats calling the closure f. Which is what I would have done.