Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the apply() function and a function call using the object of the class?

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

like image 607
Naveen Dennis Avatar asked Nov 17 '16 00:11

Naveen Dennis


People also ask

What's the difference between function call and function apply?

The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

What is the difference call () apply () and bind () in JavaScript?

Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.

What does apply () do in JavaScript?

The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Return Value: It returns the method values of a given function.


1 Answers

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!

like image 142
mgilson Avatar answered Oct 07 '22 06:10

mgilson