Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Import errors and Name errors in Python during "compile" time

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.

  1. Missing import - caught by pylint, although as a syntax error instead of an import error.
def test():
    print("Time now is ..", datetime.datetime())

pylint output:

E0602: Undefined variable 'datetime' (undefined-variable)
  1. Import present, but incorrect method used. This passes both pylint and py_compile.
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())
like image 692
Rajesh Chamarthi Avatar asked Apr 23 '19 14:04

Rajesh Chamarthi


1 Answers

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.

like image 64
Aaron Bentley Avatar answered Sep 30 '22 07:09

Aaron Bentley