I often find myself wanting to test some function by printing it as the code is run. I like to use f-strings to make the output more descriptive. Something like this:
foo = 2
bar = 5
print(f'foo * bar = {foo * bar}')
which outputs foo * bar = 10
. This is nice, but it would be really convenient to make a module that I can always import that does this for me automatically. Something like this:
eval_print.py
def eval_print(function_as_str):
print(f'{function_as_str} = {eval(function_as_str)}')
if __name__ == '__main__':
eval_print('2 + 2')
This works great until I actually import it. I ran into the problem here:
celsius.py:
from eval_print import eval_print
class Celsius:
def __init__(self, temperature = 0):
self.temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
man = Celsius()
man.temperature = 37
eval_print('man.temperature')
eval_print('man.to_fahrenheit()')
Running celsius.py
gives me a NameError exception because eval_print
doesn't have access to celsius.py
.
Is there any way to import the module that imports a module? In this case I would like to automatically import celsius.py
or whatever other module might import it to eval_print.py
.