I got example on https://www.youtube.com for function wrapping ,but it throw exception.
def addOne(myfunc):
def addOneInside(myfunc):
return myfunc()+1
return addOneInside
def oldFunc():
return 3
oldFunc=addOne(oldFunc)
print oldFunc()
error is :
TypeError: addOneInside() takes exactly 1 argument (0 given)
can any body explain what is the problem.
addOneInside does not need an argument. myfunc will be accessible via context.
Change it to
def addOne(myfunc):
def addOneInside():
return myfunc()+1
return addOneInside
The terms here are a little odd - this isn't strictly function overriding, it's function wrapping. I think what you want is a decorator. #bytesized is correct syntax-wise, but there's more to be learned about what you're attempting. Here's a great write up that might help (walks through closures, local functions and works up to decorators): http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
Related
I'm attempting to thread a function call in my Python catastr^H^H^H^H^H^Hreation, and I've read up on how to use the threading.Thread() call. My function takes a simple string argument, so theoretically it should be as easy as:
thread = threading.Thread(target = my_func, args = (string_var, ))
bearing in mind that the args() needs to be a tuple. Got it. However, it appears as though I'm still doing something wrong because I continually get the barffage from Python:
TypeError: my_func() takes 1 positional argument but 2 were given
I'm a bit stumped here. Any guidance?
Thanks!
please provide some code for us to help you.
But before you do your post could be a possible duplicate of this post.
Seems the issue is that because it's a method (thanks gribvirus74 for the idea) and I'm attempting to thread it, it won't inherit the self. And that appears to be the issue. I moved the function outside of the class and called it with the Thread(). Works fine now.
If it's a method, then you can write the following code (assuming the class name is SomeClass and it has a method called foo with one argument):
x = SomeClass()
thread = threading.Thread(target=SomeClass.foo, args=(x, 'your method argument'))
I'm currently learning curses in python, and I found this piece of code online that is confusing me.
import curses
def draw_menu(stdscr):
# do stuff
# if you want more code just let me know
def main():
curses.wrapper(draw_menu)
if __name__ == "__main__":
main()
When I run this I don't get the expected missing 1 required positional argument error, since there is no parameter being passed in the curses.wrapper(draw_menu) line. Is this a curses thing? Any help is greatly appreciated.
A function is a datatype, just as much as strings, integers, and so on.
def my_function(txt):
print(txt)
here type(my_function) # => <class 'function'>
You invoke the code inside the function when you call it with parenthesis : my_function('hello') # => prints hello
Until then you can perfectly pass a function as an argument to another function.
And that last one can call the one you passed giving it some parameters.
Like in your case, I'd guess that curses.wrapper() creates a screen interface that it passes as argument your draw_menu() function.
And you can probably use that screen object to build your curse app.
See this : Python function as a function argument?
There's a big difference between curses.wrapper(draw_menu) and curses.wrapper(draw_menu()). curses.wrapper(draw_menu) calls curses.wrapper and passes the function draw_menu into it as an argument. In contrast, curses.wrapper(draw_menu()) would call draw_menu and pass its return value into curses.wrapper.
curses.wrapper will call the function you pass it. From that link:
Initialize curses and call another callable object, func, which should be the rest of your curses-using application.
E.g., it will call draw_menu when curses is completely initialized.
Here is the signature for curses.wrapper from here.
curses.wrapper(func, /, *args, **kwargs)
It says that you need to give curses.wrapper a function reference argument followed by zero or more arguments and keyword arguments. Your code satisfies those requirements.
Python allows function signatures like this to enable developers a lot of flexibility regarding what can be passed in by the caller.
Is it possible to have the below code without raising an exception?
The hello function represents code outside my control. It is only here for the sake of clarity.
def hello():
print("hellowed")
def callsCallback(callback):
callback(*["dd"])
callsCallback(hello)
The idea is for a library to receive a callback function for when something happens. For backwards compatibility, the function being called may or may not receive parameters.
I'm aware of this answer: How can I find the number of arguments of a Python function? but I'd rather avoid inspection, if I can.
If you used *args in a wrapper function then it would never throw an exception because of the incorrect number of arguments.
def hello():
print("hellowed")
def wrapper(f):
def g(*args):
f()
return g
def callsCallback(callback):
callback = wrapper(callback)
callback(*["dd"])
callsCallback(hello)
You could use a decorator style function. This may be overkill for what you want to do.
If you don't know ahead of time how many arguments hello takes, you would have to introspect as you suggested to call the function appropriately.
so this is my function, and it doesn't work.. why?
def Oppnadjur(djurfil):
djurfil = open("djur.txt", "r")
Djur = djurfil.readlines()
Djur.sort()
djurfil.close()
Djurlista=[]
You wrote that your function should receive one parameter, djurfil. However, you clearly did not mean to do that, as you proceed to not use that parameter, overwriting it with a different value. See the Python Tutorial about how to define functions.
The error message you see means that you had called your function as you had intended, with no parameters (Opnnadjur()), but that's not how you had defined it. So Python is looking for the parameter it thinks you should be passing in.
The error would be in your calling code, not the def of the function. You need to call Oppnadjur with one parameter. The error message suggests that you are calling it with zero parameters.
You define your function with one argument (djurfil), but the argument is unused in your function so you can get rid of it.
def Oppnadjur():
djurfil = open("djur.txt", "r")
Djur = djurfil.readlines()
Djur.sort()
djurfil.close()
Djurlista=[]
I want to envoke a method in my code in a supercass, to do some subclass- specific processing before continuing on. I come to python recently from C#... there, I'd probably use an interface. Here's the gist of it (as I picture it, but it's not working):
class superClass:
def do_specific_stuff(self): #To be implemented entirely by the subclass,
#but called from the superclass
pass
def do_general_stuff1(self):
#do misc
def do_general_stuff2(self):
#do more misc
def main_general_stuff(self):
do_general_stuff1()
do_specific_stuff()
do_general_stuff2()
I have a rather complicated implementation of this; this example is exactly what I need and far less painful to understand for a first- time viewer. Calling do_specific_stuff() at the moment gives me the error
'global name 'do_specific_stuff' is not defined.
When I add 'self' as in self.do_specific_stuff I get the error
'TypeError: do_specific_stuff() takes 0 positional arguments but 1 was given.' Any takers? Thanks in advance...
It needs to be
def main_general_stuff(self):
self.do_general_stuff1()
self.do_specific_stuff()
...
The problem is that you are missing the explicit reference to self: Python thinks you mean a global function without it. Note that there is no implicit this like in Java: You need to specify it.