0

In my main() function I open a config file:

cfg = {}
execfile("config.conf", cfg)

config.conf looks like this:

x = 10

Later on, I use cfg[x], which gives me NameError: global name 'x' is not defined. I took the example from here, how I use it, looks correctly to me.

Why do I get that error?

Community
  • 1
  • 1
PMint
  • 246
  • 2
  • 13

1 Answers1

1

In the linked question, the values are accessed with strings matching the identifier names:

print config["value1"]

Likewise, you should use a string.

cfg["x"]

Example:

cfg = {}
exec("x=23", cfg)
print cfg["x"]

Result:

23
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • For completeness, `execfile('config.conf')` (with no second argument) would indeed set the value of `x` to 10, as `execfile` would use the global namespace instead of `cfg`. – chepner Nov 26 '13 at 21:10