1

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]))
Sukumar
  • 171
  • 10
  • Which part of it do you not understand? – jonrsharpe Aug 27 '18 at 20:20
  • 2
    As a general rule, whenever you see a call to `eval` or `exec`, spit over your left shoulder three times and run away, because https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice – DYZ Aug 27 '18 at 20:22
  • 6
    `eval(dir()[0])` is horrific and fragile. Do not take this as an example of what you should do in your own code. – user2357112 Aug 27 '18 at 20:23
  • @jonrsharpe `eval(dir()[0])` part – Sukumar Aug 27 '18 at 20:26
  • 2
    [`dir()[0]`](https://docs.python.org/3/library/functions.html#dir) is the first name in the current local namespace, sorted alphabetically. `eval` evaluates that name to get the object it represents. `map` then iterates though it and does `numpy.array(x) for x in eval(dir()[0])`. We then assume that there were three items in the `eval`ed object and assign the three arrays from `map` to those variables. – Patrick Haugh Aug 27 '18 at 20:26
  • 4
    [Apparently this is supposed to be an exploit vector against auto-grading of online code challenges](https://hans.codes/exploiting-side-information-codefights-challenges/), which is why they're doing things that make no sense in a normal program. – user2357112 Aug 27 '18 at 20:33

1 Answers1

4

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)
zvone
  • 18,045
  • 3
  • 49
  • 77