PyWart: NameError trackbacks are superfluous

Rick Johnson rantingrickjohnson at gmail.com
Sat Mar 16 18:39:35 EDT 2013


On Saturday, March 16, 2013 4:19:34 PM UTC-5, Oscar Benjamin wrote:
>
> NameErrors can occur conditionally depending on e.g. the
> arguments to a function. Consider the following script:
> 
>   # tmp.py
>   def broken(x):
>       if x > 2:
>           print(x)
>       else:
>           print(undefined_name)
> 
>   broken(1)

Why would anyone write code like that? That's like arming your toilet paper holder with a bomb set to explode if the RPMs of the spinning roll exceed a small threshold. Sure, you could do it, but why the hell would you? The only way your code could be any worse is by picking a random RPM threshold every morning!

 import random
 from home.bathroom import ToiletPaperHolder
 RPMS = range(100)
 
 def maybeGoBoom(event):
     maxRpm = random.choice(RPMS)
     if event.RPM > maxRpm:
         roll.explode()
    
 tph = ToiletPaperHolder()
 if not tph.has_roll():
     tph.load_roll()
 roll = tph.get_active_roll()
 roll.bind("<Spin>", maybeGoBoom)

> The traceback shows the arguments passed to the broken
> function that caused the NameError to be generated.
> Different arguments would not have generated the
> NameError. This information can be useful if the logic of
> the function in question is complicated. It also hints at
> why you were calling the function and what your code is
> trying to do.

If you want to observe your code "in action" there are much better ways than eyeball-parsing lines and lines of trackbacks. The code you posted is nonsense, maybe you can provide a better example that will convince me, but that one failed miserably.



More information about the Python-list mailing list