A better way to accomplish loop

Dave Angel davea at davea.name
Tue Feb 12 15:33:25 EST 2013


On 02/12/2013 02:59 PM, Joseph L. Casale wrote:
> I have an issue with some code I have been passed:

I had to read it about four times before I knew what you were saying. 
Maybe I still have it wrong.

>
> for (x, y) in [(a_dict1, a_tuple[0]), (a_dict2, a_tuple[1])]:
>
>
> I only noticed it as PyCharm failed to assign the str type to y, whereas it knew
> the tuples 0 and 1 item were type str.

I think you're saying that the lint-feature of PyCharm is trying to 
guess the object types, and telling you there's a conflict here.  I 
don't think you're saying that it executes incorrectly.

>
>
> In the loop it flags the passing of y into a method that expects type str. I can ignore
> it, but looking at the loop, I cant help but think there is a better way?
>

By better, you could have meant
    1) clearer for the reader
    2) runs faster or takes less memory
    3) fools PyCharm into guessing better in its checking.

If it's #3, then I'm no real help, as I've never seen a paper on the 
philosophy of the PyCharm guesser.

Still there are ways to express it differently, and maybe one of them 
will happen to please PyCharm.

Name the variables to represent what they're holding.  Those names might 
also imply type, though I wouldn't normally go out of my way to 
accomplish it.  But if the two parts of the two tuple are strings, 
perhaps the tuple as a whole might be called names, or titles, or 
authors.  However, generally a tuple is NOT expected to have the same 
type for all its elements.

for x,y in zip((a_dict1, a_dict2), a_tuple):

dicts = [a_dict1, a_dict2]
for x,y in zip(dicts, a_tuple):


-- 
DaveA



More information about the Python-list mailing list