Search code examples
pythonpython-3.xpython-2.7dictionaryeval

What does eval(dir()[0]) do in python


I came across a solution for a program in python but I couldn't understand what it does even after searching. Could someone please explain me what this statement will do.

a, b, c = map(numpy.array,eval(dir()[0]))

Solution

  • Function dir, when called without arguments returns the names of all local variables, similar to locals().keys().

    def f(y):
         print(dir())  # prints ['y']
    

    Then, obviously, dir()[0] is the name of the first of the local variables and eval(dir()[0]) evaluates the variable name, i.e. returns the first local variable's value.

    def f(y):
         print(dir())  # prints ['y']
         print(dir()[0])  # prints 'y'
         print(eval(dir()[0]))  # prints the value of y
    

    For example:

    >>> f(77)
    ['y']
    y
    77
    >>> f([1,2,3])
    ['y']
    y
    [1, 2, 3]
    

    Function map calls the first argument (which has to be callable) with each of the values in the second argument (which has to be iterable), and generates the results e.g.

    >>> for result in map(str.upper, ['foo', 'bar', 'baz']):
    ...     print(result)
    ...
    FOO
    BAR
    BAZ
    

    Combining those together, and assuming that the first local variable is a list named first_variable, then this code:

    a, b, c = map(numpy.array,eval(dir()[0]))
    

    would be the same as this code:

    a, b, c = first_variable
    a = numpy.array(a)
    b = numpy.array(b)
    c = numpy.array(c)