Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Roughly, <code>partial</code> does something like this (apart from keyword args support etc):</p> <pre><code>def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper </code></pre> <p>So, by calling <code>partial(sum2, 4)</code> you create a new function (a callable, to be precise) that behaves like <code>sum2</code>, but has one positional argument less. That missing argument is always substituted by <code>4</code>, so that <code>partial(sum2, 4)(2) == sum2(4, 2)</code></p> <p>As for why it's needed, there's a variety of cases. Just for one, suppose you have to pass a function somewhere where it's expected to have 2 arguments:</p> <pre><code>class EventNotifier(object): def __init__(self): self._listeners = [] def add_listener(self, callback): ''' callback should accept two positional arguments, event and params ''' self._listeners.append(callback) # ... def notify(self, event, *params): for f in self._listeners: f(event, params) </code></pre> <p>But a function you already have needs access to some third <code>context</code> object to do its job:</p> <pre><code>def log_event(context, event, params): context.log_event("Something happened %s, %s", event, params) </code></pre> <p>So, there are several solutions:</p> <p>A custom object:</p> <pre><code>class Listener(object): def __init__(self, context): self._context = context def __call__(self, event, params): self._context.log_event("Something happened %s, %s", event, params) notifier.add_listener(Listener(context)) </code></pre> <p>Lambda:</p> <pre><code>log_listener = lambda event, params: log_event(context, event, params) notifier.add_listener(log_listener) </code></pre> <p>With partials:</p> <pre><code>context = get_context() # whatever notifier.add_listener(partial(log_event, context)) </code></pre> <p>Of those three, <code>partial</code> is the shortest and the fastest. (For a more complex case you might want a custom object though).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload