emilchess
emilchess

Reputation: 127

How can I be warned of a potential NameError?

Here's an example of a Python script:

n, dollar, euro = map(input().split())
if n == 1:
   print(dolar / euro)  # Note the typo, 'dolar' vs. 'dollar'
else:
   print(euro / dollar)

I made a mistake ("dolar" with one 'l'). The interpreter won't inform of an error(NameError) or even a warning unless you enter n = 1.

How can I be informed of that at runtime?

Upvotes: 2

Views: 352

Answers (3)

user2665694
user2665694

Reputation:

Use Pylint:

sucmac:~ ajung$ /tmp/bin/pylint ou.py 
No config file found, using default configuration
************* Module ou
W:  3,0: Bad indentation. Found 3 spaces, expected 4
W:  5,0: Bad indentation. Found 3 spaces, expected 4
C:  1,0: Missing docstring
C:  1,0: Invalid name "n" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C:  1,3: Invalid name "dollar" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C:  1,11: Invalid name "euro" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
W:  1,18: Used builtin function 'map'
W:  1,22: Used builtin function 'input'
E:  3,9: Undefined variable 'dolar'

Upvotes: 3

Wooble
Wooble

Reputation: 90007

pylint will report this as E: 3: Undefined variable 'dolar', as well as giving you lots of useful style tips.

Python itself can't make things like this compile-time errors, since it can't really tell that you're not dynamically creating that name without running the code that leads to it. (Pylint will consider it an error even if you happen to do that, which is fine because if you write code like that you deserve to have it scored badly...)

Upvotes: 7

acjay
acjay

Reputation: 36581

Python can't inform you ahead of run-time, because there are ways of inserting "dolar" into the symbol table before that line occurs, and Python can't detect whether you have done that until it actually attempts to run the line. As Josh Lee put it, your best bet is to make a test-suite that (at the very least) exercises every line of your code.

Upvotes: 0

Related Questions