On 13/9/2013 06:24, Dotan Cohen wrote: > A function that I wrote works on a list or on a string. If the > function is passed a string, then it wraps the string in a list at the > top of the function. Is it bad form to wrap the sting in place? > > if not isinstance(someVar, list): > someVar = [someVar] > > To avoid that, I am creating a list then appending the original value: > > if not isinstance(someVar, list): > temp = someVar > someVar = [] > someVar.append(temp) > > Is my prudence unwarrented? >
yes. There are two possible issues with your first approach. The first is that somehow this is too complicated for one statement, and that something might go wrong. No worries there, as long as the object is fully formed on the right side, the "assignment" won't take place until the expression is fully evaluated. But the second one is that you now have a name that has two different meanings, depending on the path through the code. Fans of static typing might criticize this, but it's part of the essence of Python flexibility. As long as you're careful about how you implement the if-test, there's nothing wrong with doing the assignment in one statement. A separate question is whether defining the function to take these two specific types of argument is reasonable. As soon as you have an isinstnace() call, you might shortcircuit some duck-typing usage that yo hadn't imagined for your function. If you're writing a library function, to be used many places, best think about it really hard. But if it's an ordinary function, go with it. -- DaveA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor