Starting off with a few dict variables defined within a class context...
class ContextFilter(logging.Filter):
coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
u'ERROR':u'red', u'INFO':u'blue'}
colors = dict(zip([u'black', u'red', u'green', u'yellow',
u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
...I was intending to generate a derived dict variable that effectively cached the results of colors[coloring[____]]
; the intended dict contents are shown below:
{'DEBUG': '35', 'WARNING': '33', 'ERROR': '31', 'INFO': '34'}
However, using two of the dictionary constructor formats described here results in a runtime error message of NameError: name 'colors' is not defined
(in spite of colors
being defined immediately prior):
class ContextFilter(logging.Filter):
coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
u'ERROR':u'red', u'INFO':u'blue'}
colors = dict(zip([u'black', u'red', u'green', u'yellow',
u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
print(colors) # test statement; colors is in scope here
color_map = {k:colors[v] for k, v in coloring.items()}
.
class ContextFilter(logging.Filter):
coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
u'ERROR':u'red', u'INFO':u'blue'}
colors = dict(zip([u'black', u'red', u'green', u'yellow',
u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
print(colors) # test statement; colors is in scope here
color_map = dict([(k, colors[v]) for k, v in coloring.items()])
Why did the above code snippets not behave as expected? Why was colors
not in scope in the color_map
constructor, even though it appears to otherwise be in scope within the class declaration?
(Ultimately, I was able to get the desired behavior using the below code block; I'm asking this question to understand why my previous attempts at a "cleaner" solution weren't working.)
class ContextFilter(logging.Filter):
coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
u'ERROR':u'red', u'INFO':u'blue'}
colors = dict(zip([u'black', u'red', u'green', u'yellow',
u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
color_map = {}
for k, v in coloring.items():
color_map[k] = colors[v]