3

I am attempting to create a dictionary from given input variables.

I have encountered an extremely odd behavior, so I started to investigate.

I finally came up with the conclusion that the function sometimes refers to the local variables, and sometimes searches for global variables of the same names.

More specifically:

  • It refers to global variables when I create a dictionary in a loop
  • It refers to local variables when I create a dictionary one by one
  • It refers to local variables when I create a list of tuples in a loop
  • It refers to local variables when I create a list of tuples one by one

Here is a short piece of code which illustrates this problem:

x = 1
y = 2
z = 3

def func(x,y,z):
    print {var:eval(var) for var in ['x','y','z']}          # Uses globals
    print {'x':eval('x'),'y':eval('y'),'z':eval('z')}       # Uses locals
    print [(var,eval(var)) for var in ['x','y','z']]        # Uses locals
    print [('x',eval('x')),('y',eval('y')),('z',eval('z'))] # Uses locals

func(4,5,6)

Printout:

{'y': 2, 'x': 1, 'z': 3}
{'y': 5, 'x': 4, 'z': 6}
[('x', 4), ('y', 5), ('z', 6)]
[('x', 4), ('y', 5), ('z', 6)]

Can anybody please explain what am I missing here?

Thank you.

goodvibration
  • 5,980
  • 4
  • 28
  • 61

0 Answers0