is there a way to check if the variable is functions instance?
isinstance(f,function) doesnt work
Short googling shows that you can use callable function to determine weather a variable is a function or not.
>>> f = lambda x:x >>> callable(f) True >>> callable("foo") False >>> callable(123) False
so trying the naive way of 4 lines of code doesn't work. have we learnt what to do now?
what utility function exactly?
Anyway this would not be necessary.
The code here is rather short.
Can we assume that all the function get the same type, and return the same type?
Should we check that the input is indeed a tuple of functions? I mean, should we check that the tuple doesn't include other types?
What would be the expected output in case the input is just one function?
I tried to make a loop that goes through the functions in a reversed order and composes the functions one by one.
I used this line:
for func in funcs: composed=func(composed)
but I get an error "local variable 'composed' referenced before assignment". How am I supposed to define "composed"?
I already tried:
But then I get a different error "unsupported operand type(s) for -: 'function' and 'int'"
why do I get "TypeError: 'tuple' is not callable" while trying to compose 3 (or more) functions, when my code ends with this recursive line:
The is no 'tuple' in use. comp2 is 'callable' for sure, since composing 2 functions (only) does work. So I wonder if funcs[:-2] isn't callable, and why.
>>> t = (1, 2, 3) >>> t[:-2] (1,) >>> type(t[:-2]) <class 'tuple'>
Slicing a tuple always returns a tuple. In the code above, You could access t[:-2], or obviously you could access t directly (which won't create an unneeded tuple instance).
10x, indeed I mistakenly assumed that funcs is a list type instead of tuple.
Given your lighting I changed my recursive call to tuples form:
but still get the same error "TypeError: 'tuple' is not callable"
comp2 isn't the problem, since I went ahead and checked if this castrated line works with no error:
But it still returns the same callable issue. So it seems that slicing action isn't acceptable for some reason in tuples, as arguments in recursive calls (?)
Again, the simple line:
fails because funcs[:-2] is a tuple, and compose expects an arbitrary number of callable arguments, not a tuple. These arguments are then automatically wrapped in a tuple inside the compose function.
See section 4.7.3 (Arbitrary Argument Lists) of the Python tutorial (sorry, I can't post links) and perhaps play with this form a little in the interpreter to understand how it works.
Also worth mentioning:
You can unpack a tuple to separate arguments like so:
>>> def test(*args): assert all(isinstance(x, int) for x in args) print("all good") >>> t = (1, 2) >>> test(t) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> test(t) File "<pyshell#14>", line 2, in test assert all(isinstance(x, int) for x in args) AssertionError >>> test(*t) all good