0

I have a dictionary that contains several items. Inside a method, I want to make these available. This is what I am doing right now

def myFunc(stuff):        
    for foo, bar in stuff.items():
        locals()[foo] = bar
    testVar

foo = {'testVar': 0}
myFunc(foo)

However, I get (inside python 2.7)

NameError: global name 'testVar' is not defined

Perhaps doing this, I am not accessing the function scope but the local scope outside of it? How can I access the function scope?

Emphasis

This is an abstracted problem to show exactly what I want. In this scenario, ofc., accessing a dictionary would be the correct solution. But let's just assume that I have some reasons for doing this. The question is not:

  • How can I access variables I stored in a dictionary? Should I use the dictionary?

It is

  • Given that I operate inside a function, and want to access the variables directly in that function, how do I have to unzip the dictionary?
FooBar
  • 15,724
  • 19
  • 82
  • 171
  • Your indenting is severely off. – A.J. Uppal May 26 '14 at 11:48
  • Fixed the indenting - had some issues with the WYSIWYG editor (that is, I can't count to four). – FooBar May 26 '14 at 11:49
  • 1
    No, you cannot add new local names to a function; `locals()` is read-only. The scope of `testVar` is determined at parse time, not at runtime. – Martijn Pieters May 26 '14 at 11:50
  • Just use a regular dictionary, don't try to create new names on the fly. – Martijn Pieters May 26 '14 at 11:51
  • This is a very abstracted problem, the long story is long. I want these to be variables and not a dictionary. I have to temporarily zip them in the dictionary for saving purposes, but I want to have them "ready", not inside some dictionary. – FooBar May 26 '14 at 11:55
  • Looks like you wanted to use a `**kwargs` call signature instead: `def myFunc(testVar): ...` and `myFunc(**foo)`. – Martijn Pieters May 26 '14 at 11:59
  • Martijn, you are wrong in that `locals()` is read only, at least for 2.7. – FooBar May 26 '14 at 11:59
  • 1
    @FooBar: No, you misunderstand the nature of the dictionary. You can alter it, but **no locals are set** from it. It is a one-way street only. See the other post I dupe-closed this question of. – Martijn Pieters May 26 '14 at 12:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54440/discussion-between-foobar-and-martijn-pieters). – FooBar May 26 '14 at 12:09

1 Answers1

0

The issue has been resolved now after some chatting, but just for the sake of history:

  • There is no nice way of doing so.
  • While locals() seem to be working outside of function space in older Python, there is nothing similar inside the function scope.

Quite a drawback I would say, personally, but whatever.

FooBar
  • 15,724
  • 19
  • 82
  • 171