[IPython-dev] Cell magic for closures

Thomas Kluyver takowl at gmail.com
Fri May 17 08:14:57 EDT 2013


Hmm, that's an interesting idea. Running it under a def might cause some
other problems, like UnboundLocalErrors when you try to modify variables.
Another approach might be a cell magic that remembered what globals were
defined at the start of the cell, and removed any new ones after running
the cell.

Perhaps it would be best to collect some examples of cases where this would
be useful, to see what's the best way to do it. You can of course write an
extension for it:
http://ipython.org/ipython-doc/stable/config/extensions/index.html

Best wishes,
Thomas


On 17 May 2013 04:55, Jeffrey Tratner <jtratner at gmail.com> wrote:

> Hi all,
>
> I've been using ipython notebook for a project at work and I really enjoy
> it. The only issue that I have is that sometimes using the code in cells
> and editing code on the fly means that you unintentionally define globals
> without meaning to. Clearly you can define a new function, but that also
> pollutes the name space and just feels weird.
>
> Javascript has a convention of wrapping code in an immediately executed
> function and I know that someone has proposed adding something like a given
> keyword to python to accomplish something similar, but it'd be nice to be
> able to do it without adding an extra level of indentation and to be able
> to do it in 2.7.
>
> I'm imagining a syntax like %%closure that consumes a cell and executes it
> as if it were underneath a def statement. This has the benefit of reducing
> the level of indentation as well as doing things like this:
>
> within_cell_variable = xyz
>
> # do something
>
> del within_cell_variable
>
> ---
>
> or if you need to iterate over something, suddenly you've polluted the
> namespace with a random off variable.
>
> I'd love to have this, I think it would be useful in the context of a
> notebook and reduce the amount of def statements used only to encapsulate
> variables. It's also kinda magical I guess.
>
> Best,
>
> Jeff
>
> _______________________________________________
> IPython-dev mailing list
> IPython-dev at scipy.org
> http://mail.scipy.org/mailman/listinfo/ipython-dev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20130517/44725d3d/attachment.html>


More information about the IPython-dev mailing list