'Is there a way to ignore "TypeError - 0 positional arguments but 1 was given"? [duplicate]
I understand why this is happening, because callback doesn't take any arguments, but I'm passing one in x.
But is there a stop this error from happening? i'm making an event manager, and sometimes you don't always need the extra information that is passed through the parameters.
import time
callbacks = {
"on_foo": []
}
def callback_register(name, callback, *args, **kwargs):
def cb(*args, **kwargs):
return callback(*args, **kwargs)
callbacks[name].append(cb)
def callback_unregister(name):
del callbacks[name]
def callback_exists(name):
return name in callbacks
def callback_call(name, *args, **kwargs):
for cb in callbacks[name]:
cb(*args, **kwargs)
def foo():
print("FOO!")
called_at = time.time()
callback_call("on_foo", called_at)
callback_register("on_foo", lambda x: print(f"foo was called at {x}"))
callback_register("on_foo", lambda: print(f"foo has been called!")) #errors
# no need for the called_at variable since it's not being used in this callback
foo()
I have solved my answer and would like to post an answer.
Solution 1:[1]
Like a regular function in Python, which can take variable number of arguments using *args , you could add *args to lambda arguments.
callback = lambda *args: print(5)
Edit: This question was abruptly changed. So updated answer:
lambda *args: print(f"foo has been called!")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
