I have a YAML config file, which contains a dictionary, like so:
"COLUMN_NAME": column_function
It maps strings to functions (which exist and are supposed to be called).
However, when I load it using yaml
, I see that the loaded dictionary now maps strings to strings:
'COLUMN_NAME': 'column_function'
Now I cannot use it as intended - 'column_function'
doesn't point to column_function
.
What would be a good way to load my dict
so that it maps to my functions? After searching and reading a bit on this issue, I'm very cautious about using eval
or something like that, since the config file is user-edited.
I think this thread is about my issue, but I'm not sure on the best way to approach it.
getattr
andsetattr
are out, I think, because they operate on instantiated objects, whereas I have a simple script.globals()
,vars()
andlocals()
provide me withdict
s of variables, and I suppose I should useglobals()
, according to this.
Should I look up the string in them for each of key-value pairs in my config dict
? Is this a good way:
for (key, val) in STRING_DICTIONARY.items():
try:
STRING_DICTIONARY[key] = globals()[val]
except KeyError:
print("The config file specifies a function \"" + val
+ "\" for column \"" + key
+ "\". No such function is defined, however. ")