Reputation: 18818
Can you catch import / name and other errors in python using a (linting) tool or a compilation step?
The other option is to make sure all possible code paths are tested (This is not always feasible, especially for large existing code bases and other reasons)
Here are some examples.
syntax error
instead of an import error
.def test():
print("Time now is ..", datetime.datetime())
pylint output:
E0602: Undefined variable 'datetime' (undefined-variable)
from datetime import datetime
def test():
print("Time now is ..", datetime.today2())
Edit: To add one more option.
Doing an import *
shows some errors, but not errors in statements which are inside the functions.
This error is reported
from datetime import datetime
print("today2", datetime.today2())
Error :
Python 3.7.0 (default, Aug 22 2018, 15:22:56)
>>> from test import *
...
print("today2", datetime.today2())
AttributeError: type object 'datetime.datetime' has no attribute 'today2'
>>>
This is not.
from datetime import datetime
def test():
print("Time now is ..", datetime.today2())
Upvotes: 8
Views: 1535
Reputation: 1380
In my experience, flake8 does a great job of catching missing imports and name errors. In order to catch missing imports, you must not use wildcard imports like "from foo import *", since it cannot guess which names that will create. Also, it cannot do these detections while syntax errors exist, so you have to fix those first.
Upvotes: 3
Reputation: 1156
Unlike c++ which is a compiled language, python is an interpreted language. Which means it doesn't have compile phase. It interpreted code line by line.
According to that, you didn't find the errors until you reach them in runtime.
If you want that errors appears, you should somehow path throw every line of your code. The best approach is using test libraries with 100% test coverage.
For more information look at this question and it's answers.
Upvotes: 3