In a module I am writing, I have a need for checking that incoming data matches particular requirements and formats. I thought I knew a good way to do this, but I need to add logging functionality and it made me realise I must be writing my code improperly. A MWE of what I am currently doing is:
string1 = 'Hello, World!' # represents something like a column name in an incoming dataframe
string2 = 'Hello, World?' # represents what the column name should be according to an incoming config file
if string1 != string2:
raise ValueError('Input from string1 does not match expected value given in string2')
That works perfectly, and the raised error can be grabbed by my pytest functions as well. But it is not part of a try
except
sequence, and I dont see how it can be. try
doesn't behave like an if
and except
requires the specific error to actually be raised first.
This poses a problem because I dont know how to capture the raised error with python's logging
module without needless code duplication. The best I can do is:
import logging
string1 = 'Hello, World!' # represents something like a column name in an incoming dataframe
string2 = 'Hello, World?' # represents what the column name should be according to an incoming config file
if string1 != string2:
logging.error('Input from string1 does not match expected value given in string2')
raise ValueError('Input from string1 does not match expected value given in string2')
But that is two, nearly identical lines to do the same thing. logging.error
doesnt actually halt the code, which I need to happen, and I cant find a way to capture the raise ValueError(...)
with logging
.
Obviously, with this example, logging
is just going to print to the terminal, but ultimately, it will be printing to a file (and I know how to do that).
What is the best way to write such a test of variables to have both logging and raised error functionality?