[omaha] with blocks and conditions

David Gilman davidgilman1 at gmail.com
Fri Nov 14 23:23:48 CET 2014


For Python 3.3 and onward, you have contextlib.ExitStack.

with ExitStack() as stack:
    if condition:
        stack.push(open(path))
    do_stuff()

On Fri, Nov 14, 2014 at 3:29 PM, Aaron Keck <keckbug at gmail.com> wrote:
> I've found myself trying to find a cleaner way of doing this:
>
> if *condition_is_true*:
>     with *file* as *fp:*
> *        do_stuff()*
> else:
> *    do_stuff()*
>
>
> Is there a reasonable way to wrap some code using *with* but only in
> certain circumstances? Most of the scenarios I've bumped up against have
> had some sort of alternate solution that works well, but I'm still curious.
>
>
> -Aaron
> _______________________________________________
> Omaha Python Users Group mailing list
> Omaha at python.org
> https://mail.python.org/mailman/listinfo/omaha
> http://www.OmahaPython.org



-- 
David Gilman
:DG<


More information about the Omaha mailing list