8

Consider Atom to be a class where

  • form.name is a string
  • convert returns a list of values

What is the difference between the following two lines?

  • apply(Atom, [form.name] + list([convert(arg, subst) for arg in list(form.args)]))

  • Atom(form.name, [convert(arg, subst) for arg in form.args])

From documentation,

apply(...) apply(object[, args[, kwargs]]) -> value
Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a call() method.

I am not able to understand the difference between the two lines. I am trying to find an equivalent code for apply(Atom, [form.name] + list([convert(arg, subst) for arg in list(form.args)])) in Python 3.5

Naveen Dennis
  • 1,223
  • 3
  • 24
  • 39

1 Answers1

18

apply is an old-school1 way of unpacking arguments. In other words, the following all yield the same results:

results = apply(foo, [1, 2, 3])
results = foo(*[1, 2, 3])
results = foo(1, 2, 3)

Since you're working in python3.5 where apply no longer exists, the option is not valid. Additionally, you're working with the arguments as a list so you can't really use the third option either. The only option left is the second one. We can pretty easily transform your expression into that format. The equivalent in python3.5 would be:

Atom(*([form.name] + [convert(arg, subst) for arg in list(form.args)]))

1It was deprecated in python2.3!

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • It works.. but can you tell me which concept is used here so that I can read about it. What is Atom(*...)? What does the * represent? – Naveen Dennis Nov 17 '16 at 00:42
  • Got it! http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-parameters – Naveen Dennis Nov 17 '16 at 00:44
  • 1
    @Dennis -- That's how we now unpack arguments in modern python. I've added a link above where you can read more about it in the python tutorial – mgilson Nov 17 '16 at 00:44
  • 3
    @Dennis -- Also, be a little careful with that link you posted. Specifically, that link specifies what it means to have a `*` at the function definition point. This question is more about what it means to have a `*` at the function _call_ point. They're closely related concepts (closely related enough that it's easy to overlook the fact that they're different when you've been working with it for a while), but they are distinct things that can be understood separately. – mgilson Nov 17 '16 at 00:47