PMint
PMint

Reputation: 246

Python: NameError: global name 'x' is not defined

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?

Upvotes: 0

Views: 2233

Answers (1)

Kevin
Kevin

Reputation: 76194

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

Upvotes: 1

Related Questions