OOP - how to abort an __init__ when the initialisation code fails ?

Peter J. Holzer hjp-python at hjp.at
Tue Nov 5 14:52:59 EST 2019


On 2019-11-04 18:18:39 -0300, Luciano Ramalho wrote:
> In addition, as Rob said, it is usually a bad idea to wrap several
> lines of code in a single try/except block

I disagree with this. While it is sometimes useful to wrap a single
line, in my experience it rarely is. The scope of the try ... except
should be a unit from a semantic point of view. For example, if you
open a file and write some data to it, you could write:

    try:
        f = open("a.file", "w")
    except OSError as e:
        ... handle exception
    try:
        f.write("some")
    except OSError as e:
        ... handle exception
    try:
        f.write("data")
    except OSError as e:
        ... handle exception
    try:
        close(f)
    except OSError as e:
        ... handle exception

But not only is this hard to read and ugly as heck, what would be the
point? 

Much better to write:

    try:
        with open("a.file", "w") as f:
            f.write("some")
            f.write("data")
    except OSError as e:
        ... handle exception

Or maybe don't catch it here at all but just let it bubble up until it
hits a level where dealing with it makes sense from the user's point of
view (who may not care about an individual file, but about the task they
instructed the program to perform).

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20191105/0581f17a/attachment.sig>


More information about the Python-list mailing list