micseydel wrote: rovf wrote:
So this would be kind of:
- Code: Select all
data # See whether it behaves like a list
# data is not a list
# Now it is ensured that data is a list
First, you should catch the exact exception you'd get rather than a blanket one. Here, you probably want to catch a TypeError.
I thought of this, but could it be something else besides TypeError? Well, data could be None, but in this case, we would proceed with [None]*3 , and this would be caught shortly after anyway.
micseydel wrote:If you post a bit more of your code for the use case we can advise you better, if you aren't sure of what you want after my attempt at explaining. But typically we do adhere to duck typing principals.
Adhering to duck typing is always a good idea, as I will be more flexible in how I can use my function later. This was also the reason why I liked the idea with the exception. Now to what I'm exactly doing (because, as you already might have guessed, the example code I posted was stripped down to the minimum necessary which I thought was needed to demonstrate the problem):
I have a function, which - as one parameter - expects a list of 3 items. Seeing it from the viewpoint of duck typing, it doesn't need to be a list, but can be anything which can be indexed with ,  and . No other properties of a list are needed here. In practice, the actual parameter is currently always a list.
There are several points in the application, where this function is called with a list, where by design all 3 elements must have the same value. It would be convenient to allow here to write only one value here. I thought of three solutions for this:
(a) Have the caller write this explicitly, for example as
- Code: Select all
(b) Provide a (differently-named) cover function, which expects a scalar, turns this scalar into a list and calls myFunction with the list as argument
(c) Make myFunction intelligent enough to accept either a scalar or a list
I settled for (c), because I prefered this way of usage, and it seems to be also the most interesting one (I'm using the project to learn Python). Therefore, I need to insert a few lines in the function body, which test, whether the parameter is a list or a scalar, and if it is a scalar, turn it into an list. If it is already a list, nothing needs to be done. After this, the function is executed as before, but guaranteed to operate on a list.
Did I explain clearly enough my intent? I can post the actual code of my function if necessary, but I fear that it would just unnecessarily distract from the problem at hand.