[Share Code] defensive tuple param idea
No revelation here for the guys who are not beginners in Python . And maybe there is a better way to do it.
But when you pass tuples as params to your own methods/func, it's all ok as long as you pass more than one value in your tuple. If you pass like (10,1) it will be ok. But if you pass one value like (10) it will not be ok. Is not a tuple. It has to be (10,)
I do know this, but it's frustrating as I forget sometimes. I was doing something today exactly like this.
Anyway, I did the below. I hope it helps, or maybe better ideas emerge
def accept_a_tuple(tp): try: for v in tp: print(v) except: print('this fails') def accept_a_tuple_better(tp): # headache saver when passing a single value tuple without a comma if not isinstance(tp, tuple): tp = (tp,) for v in tp: print(v) accept_a_tuple((20,)) # is ok, we remember the comma accept_a_tuple((10)) # this fails, is not a tuple accept_a_tuple_better((10)) # i think this is a better way
ccc last edited by
def mega_accept_a_tuple(tp): try: print(tuple(tp)) except TypeError: print(tuple((tp,)))
@ccc , yes sure. I am not sure what is more Pythonetic approach. I just wrote the post because I think a lot of beginners like me get particular tripped up on this.
I had a function that took a variable amount of of items in a tuple. When I started passing one item of course it starting going wrong because I forgot the stupid comma.
It is a strange syntax. I had my first run in with this problem adding right and left items to the menu in ui.View :)
cook last edited by
@Phuket2 the syntax may be strange but considering that parenthesis are used for other things it isn't...
>>> (0) 0 >>> (0,) (0,)
@cook , yeah. I know. Just a decision made that it was a lesser evil I guess. I am ok with it, it's just a hard one as a new Python programmer I think. Well it was for me anyway 😱