I'm having the problem of a button executing its' command when it's created. To stop this I have got a function, which can stop this behavior
This is the function which makes functions callable without being executed while creating my button. Usually it works fine but with some functions it seems to deny randomly any input! Here is the code:
class Callable(object):
def __init__(self, func, *args, **kwds):
self.func = func
self.args = args
self.kwds = kwds
def __call__(self, *args, **kwds):
return self.func(self.args)
def __str__(self):
return self.func.__name
It seems to be totally randomly which questions are accepted and which aren't. I'm really desperate, because it takes a lot of time to write a kind of synonym of this class, I adapt them with the number of args
and kwds
, then it works ok. But now I'm coming to a point where I don't know how many args I'm going to pass, so this won't work any more.
Question:
- Why does this class doesn't accept every function?
- How can I change this behaviour?
I believe that's what you're looking for:
You need to unpack it with the
*
operator, and**
for keyword arguments. That way you pass your variables and the function's call variables.UPDATE:
For python versions older than 3.5, this will work:
Using this solution, you will first give the variables acquired by the
__init__
then the variables passed to the__call__
.Please consider using the following class. It allows you to specify positional arguments and keyword arguments at the time of either instance creation or instance invocation (creating a new instance or calling it). Since it is ambiguous what would be meant if either types of arguments were specified at both times, the class refuses to guess what order or priorities were intended and raises a
RuntimeError
to prevent undefined behavior. Also, the__str__
method should still work if your function or other callable object does not have a__name__
attribute.You might also want to take a look at
functools.partial
for a well-defined object with very similar behavior. You may be able to avoid defining your ownCallable
class and use thefunctools
module instead. That way, there is less code that you have to manage in you project.Your class is used to provide additional context to tkinter callbacks so the callback can actually do something useful. You almost have it right except that you need to unpack the original args and kwds when calling the function. Also, don't include any args in
__call__
because you don't accept any.This can also be done without a class, using lambdas instead