Hi all,

for everyone tired of manually inserting end() statements in the code,
here's a little neat workaround.
The problems I was having arose from the fact that begin('...')
statements always have to be manually closed by end() to maintain
consistency with output indentation. While tedious, this is something
that you can manage. It's getting messy when exceptions are raised,
though, and your code doesn't reach end(); for example:

================= *snip* =================
from dolfin import begin, end, info


def main():
    begin('My message')
    begin('Nested message')
    a = 3.14
    info('a = %f' % a)
    info('2*a = %f' % (2 * a))
    info('a/0 = %f' % (a / 0))
    end()
    end()

try:
    main()
except:
    info('whoops')
    pass
info('byes')
================= *snap* =================

-- The `a / 0` makes sure that end() is never executed, so you end up
with over-indented output after main(). One way to deal with this is
to insert except in main() and call end() explicitly; even better
suited is the `finally` keyword.

The cleanest way to deal with this is using Python's `with`:

================= *snip* =================
from dolfin import begin, end, info


class Message:

        def __init__(self, string):
            self.string = string
            return

        def __enter__(self):
            begin(self.string)
            return

        def __exit__(self, type, value, traceback):
            end()
            return


def main():
    with Message('My message'):
        with Message('Nested message'):
            a = 3.14
            info('a = %f' % a)
            info('2*a = %f' % (2 * a))
            info('a/0 = %f' % (a / 0))

try:
    main()
except:
    info('whoops')
    pass
info('byes')
================= *snap* =================

`with` guarantees that __exit__ (and hence end()) is called every
time, plus enforces indentation of code the output of which is also
indented.

The C++ equivalent of this would be using simple scopes; manually
calling end() (and arising inconsistencies) could be entirely
eradicated this way.

Cheers,
Nico
_______________________________________________
fenics mailing list
[email protected]
http://fenicsproject.org/mailman/listinfo/fenics

Reply via email to