And now for something completely different … - do you guys remember that line from Monty Python? It seemed an appropriate label for a Python problem, as the reason I chose to learn Python rather than C++ or Java is because Python is named after Monty P.
Anyway, here’s the problem I would like some help with pls. In the last 12 seconds or so of the “Cleaning Up” lecture in the “Exceptions” section of the “Python Complete Mastery” course, Moshe entered some code including a “finally” statement. I have replicated the statements on VSCode as follows:
The bizarre thing is that pylint puts a squiggly red line under the very last statement, saying “Using variable ‘file’ before assignment”. When I put the code into debug it all runs fine, nothing crashes whatever I enter for the “age” the code requests.
Why is Pylint dishing up a red squiggly line under my file.close statement, pls ? Does anybody know, please?
It could be that pylint had detected that the open method may throw before you actually assign its result to the file variable. If that happened the file variable would be unassigned when you entered the finally block.
Thanks for your help, both of you, it is much appreciated.
This is most odd. When I copy and paste the above code from D0114R into VSCode, Pylint underlines the last occurrence of the word “file”, in the finally clause, in a squiggly red line (just as it did for my original version of the block of code.
When I add the statement file = open(“app.py”) before the try block, the problem goes away ie no Pylink squiggly red line.
If either of you have any observations on this, I would be interested to hear them, otherwise, thanks again for your help and I hope your day is really great … or even better
For the record, that gives further proof that it was detecting the possibility that the open function itself could throw one of the errors leading to the file variable never getting initialized. In general you want try blocks to be as narrow as possible. In this case, the part that can throw is conversion to int from the string input so it is the only part that belongs in the try block.
I know this may sound a bit weird but, try changing the name of the variable and check, not sure if this will help but in JavaScript certain variable names can not be used, but i’m pretty sure it won’t help but give it a try.