Suppressing source code in Python warnings

Python has a great way to print warnings without raising an exception (which would halt the program). However, it prints the line of source code that generated the warning, which is a) unnecessarily verbose, and b) universally useless because it's always just the call to the warnings module which you're already looking at the output of. Suppressing it is somewhat complex, but easy to copy/paste; just put this verbatim at the top of your file (not inside a function, or you'll wind up with recursion issues):

import warnings
 
formatwarning_upstream = warnings.formatwarning
def my_formatwarning(message, category, filename, lineno, line=None):
    return(formatwarning_upstream(message, category, filename, lineno, line=''))
warnings.formatwarning = my_formatwarning

Now you can call warn() just like you normally would (the second example just restates the defaults):

warnings.warn("Something isn't quite right, but we don't have to abort over it.")
warnings.warn("Something isn't quite right, but we don't have to abort over it.", UserWarning, stacklevel=1)

Indirect variables in shell scripts

Normally, you'd use an associative array for this (including BASH) instead of manually embedding a variable in another variable, but this solution works in POSIX environments like regular Bourne shell (and BASH's emulation of it):

favorite_color_joe=gold
favorite_color_jane=blue
 
person=${1}
 
target_interface=`eval echo \$favorite_color_${person}`
programming.txt · Last modified: 2018/04/09 11:11 by dlicious
 
Except where otherwise noted, content on this wiki is licensed under the following license: GNU Free Documentation License 1.3
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Run by Debian Driven by DokuWiki