Python Forum

Full Version: Object reference in Dict - not resolved at runtime
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here is my code:

total_runtime = None
mail_pfx = "dVDS FULL5 CN"

mail_subj = {
	'completed' : f"{mail_pfx} : [INFO] Refresh completed successfully in: {total_runtime}.",
	'warnissues' : f"{mail_pfx} : [ALERT] Refresh completed with issues in: {total_runtime}"
	}

class Stopwatch():

	def __init__(self):
		self.tick = 0
		self.tock = 0
		self.time = 0

	def start(self):
		self.tick = time.perf_counter()

	def stop(self):
		self.tock = time.perf_counter()
		self.time = timedelta(seconds=math.ceil(self.tock-self.tick))

	def __str__(self):
		return str(self.time)

total_runtime = Stopwatch()
total_runtime.start()
total_runtime.stop()

print(mail_subj['warnissues'])
This is printing "dVDS FULL5 CN : [ALERT] Refresh completed with issues in: None"

I want it to resolve the object at runtime instead of compile time, is there any way to do this?
f-strings are just special ways to create strings. They're not objects. Any variables or expressions inside the string are evaluated at runtime exactly once, not later. Compare:

author = 'Alice'
string1 = author
string2 = f'{author}'

author = 'Bonnie'
print(string1)
print(string2)
The strings assigned to both string1 and string2 are immutable and not re-evaluated later even if author is subsequently modified. Both print statements will produce "Alice". Your string is being evaluated at runtime. It's just happening before all the variables in it are set to what you want to display.

For your code, you could move the dictionary assignment to be after total_runtime is set. Or you could leave the variable out of the dictionary and append it in the print. Something like:

mail_subj = {
    'completed' : f"{mail_pfx} : [INFO] Refresh completed successfully in:",
    'warnissues' : f"{mail_pfx} : [ALERT] Refresh completed with issues in:"
    }
[...]
total_runtime.stop()
print(mail_subj['completed'], total_runtime)
Thank you kindly!